<template>
  <div class="field-survey">
    <div class="preview-button-container">

      <el-button :disabled="!hasUnknownResults" type="primary" @click="syncResults">
        {{ '定性同步' }}
      </el-button>
      <el-button type="primary" @click="dialogVisible = true">符号</el-button>
      <el-button type="primary" @click="toPreviewFieldSurvey">预览</el-button>
      <el-button type="primary" @click="toSignature">签名</el-button>
    </div>
    <!-- 使用el-tabs组件 -->
    <el-tabs v-model="activeTab" class="survey-tabs" type="border-card">
      <el-tab-pane label="基本信息" name="basic">
        <div class="form-content">
          <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
            <!-- 第一行 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="受检单位">
                  <div class="company-input-container">
                    <el-input v-model="formData.inspectedCompany" class="company-input" />
                    <el-button
                      :disabled="!formData.inspectedCompany?.trim()"
                      link
                      size="small"
                      type="primary"
                      @click="openQccSearch"
                      >查询
                    </el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="委托单位">
                  <el-input v-model="formData.entrustCompany" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二行 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="社会信用代码" prop="creditCode">
                  <el-input
                    v-model="formData.creditCode"
                    placeholder="请输入18位社会信用代码"
                    @input="validateField('creditCode')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="法人/负责人">
                  <el-input v-model="formData.legalPerson" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第三行 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="单位注册地址">
                  <el-input v-model="formData.registeredAddress" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <template #label>
                    <el-tooltip
                      content="可添加多个地址，输入后按回车添加标签"
                      effect="light"
                      placement="top"
                    >
                      <span style="display: inline-flex; align-items: center"> 技术服务地址 </span>
                    </el-tooltip>
                  </template>
                  <el-input-tag
                    v-model="workplaceAddresses"
                    :trigger-on-focus="false"
                    class="!w-full"
                    placeholder="输入地址后回车添加标签"
                    size="default"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第四行 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="投产时间">
                  <div style="display: flex; align-items: center; gap: 8px; width: 100%">
                    <el-select
                      v-model="productionDateMode"
                      placeholder="选择精度"
                      style="width: 110px"
                    >
                      <el-option label="年" value="year" />
                      <el-option label="年月" value="month" />
                      <el-option label="年月日" value="date" />
                    </el-select>
                    <el-date-picker
                      v-model="formData.productionDate"
                      :format="productionDisplayFormat"
                      :type="productionPickerType"
                      :value-format="productionValueFormat"
                      placeholder="选择日期"
                      style="flex: 1"
                    />
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位性质">
                  <el-tree-select
                    v-model="formData.companyNature"
                    :data="enterpriseTypeOptions"
                    :default-expanded-keys="getExpandedKeys()"
                    :expand-on-click-node="false"
                    :render-after-expand="false"
                    placeholder="请选择单位性质"
                    style="width: 100%"
                    @visible-change="handleTreeSelectVisibleChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第五行 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="所属行业">
                  <div class="company-input-container">
                    <el-select
                      v-model="formData.industry"
                      :loading="industryLoading"
                      :remote-method="searchIndustries"
                      filterable
                      placeholder="请输入关键字搜索行业"
                      remote
                      reserve-keyword
                      style="width: 100%"
                      @change="handleIndustryChange"
                    >
                      <el-option
                        v-for="item in industryOptions"
                        :key="item.id"
                        :label="item.xiaoLeiCode + item.categoryName"
                        :value="item.xiaoLeiCode + item.categoryName"
                      >
                        <div
                          style="
                            display: flex;
                            justify-content: space-between;
                            align-items: center;
                            width: 100%;
                          "
                        >
                          <span style="flex: 1; min-width: 0; margin-right: 8px">
                            {{ item.xiaoLeiCode + ' ' + item.categoryName }}
                          </span>
                          <span
                            v-if="item.description"
                            :title="item.description"
                            style="
                              flex-shrink: 0;
                              color: #8492a6;
                              font-size: 12px;
                              max-width: 550px;
                              overflow: hidden;
                              text-overflow: ellipsis;
                              white-space: nowrap;
                            "
                          >
                            {{ item.description }}
                          </span>
                        </div>
                      </el-option>
                    </el-select>
                    <el-button link size="small" type="primary" @click="openIndustry"
                      >资料
                    </el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="在册职工总人数" prop="totalEmployees">
                  <el-input
                    v-model="formData.totalEmployees"
                    placeholder="请输入在册职工总人数"
                    type="number"
                    @input="handleTotalEmployeesChangeAndValidate"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="风险等级">
                  <div class="company-input-container">
                    <el-select
                      v-model="formData.riskLevel"
                      :class="{ 'flash-border': riskLevelFlashing }"
                      placeholder="请选择风险等级"
                      style="width: 100%"
                    >
                      <el-option label="严重" value="严重" />
                      <el-option label="一般" value="一般" />
                    </el-select>
                    <el-button link size="small" type="primary" @click="openRiskLevel"
                      >资料
                    </el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="劳务派遣人员" prop="dispatchedWorkers">
                  <el-input
                    v-model="formData.dispatchedWorkers"
                    placeholder="请输入劳务派遣人员数量"
                    type="number"
                    @input="validateField('dispatchedWorkers')"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第六行 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="企业规模">
                  <div class="company-input-container">
                    <el-select
                      v-model="formData.companySize"
                      :class="{ 'flash-border': companySizeFlashing }"
                      :loading="companySizeLoading"
                      placeholder="请选择企业规模"
                      style="width: 100%"
                    >
                      <el-option label="大型企业" value="大型企业" />
                      <el-option label="中型企业" value="中型企业" />
                      <el-option label="小型企业" value="小型企业" />
                      <el-option label="微型企业" value="微型企业" />
                    </el-select>
                    <el-button link size="small" type="primary" @click="openCompanySize"
                      >资料
                    </el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="管理联系人">
                  <el-input v-model="formData.contactPerson" placeholder="请输入管理联系人" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 新增管理联系人信息行 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系人电话" prop="contactPhone">
                  <el-input
                    v-model="formData.contactPhone"
                    placeholder="请输入联系人电话"
                    @input="validateField('contactPhone')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人邮箱" prop="contactEmail">
                  <el-input
                    v-model="formData.contactEmail"
                    placeholder="请输入联系人邮箱"
                    @input="validateField('contactEmail')"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 新增联系人邮箱行 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <!-- 可以在这里添加其他字段，或保持空白 -->
              </el-col>
            </el-row>
            <!-- 第七行 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="职卫管理人">
                  <el-input v-model="formData.healthManager" placeholder="职卫管理人" />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 第八行 -->
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="调查备注">
                  <el-input
                    v-model="formData.surveyRemarks"
                    :rows="3"
                    placeholder="请输入调查备注"
                    type="textarea"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="岗位信息" name="job">
        <JobSurvey ref="jobSurveyRef" :operationType="operationType" />
      </el-tab-pane>
      <el-tab-pane label="原辅材料" name="materials">
        <div class="equipment-content">
          <!-- 添加新增按钮 -->
          <div class="mb-4">
            <el-button type="primary" @click="handleAddMaterial">新增原辅材料</el-button>
          </div>
          <el-table :data="materialsList" :span-method="materialsSpanMethod" border>
            <el-table-column align="center" width="400">
              <template #header>
                <span>原辅材料名称</span>
                <span class="required-star">*</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(materialsList, 'materialName')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.materialName" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="180">
              <template #header>
                <span>用量</span>
                <span class="required-star">*</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(materialsList, 'usage')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.usage" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="180">
              <template #header>
                <span>物理状态</span>
                <span class="required-star">*</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(materialsList, 'physicalState')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.physicalState"
                  placeholder="请选择物理状态"
                  filterable
                  allow-create
                  style="width: 100%"
                >
                  <el-option label="固态" value="固态" />
                  <el-option label="粉状固态" value="粉状固态" />
                  <el-option label="粒状固态" value="粒状固态" />
                  <el-option label="片状固态" value="片状固态" />
                  <el-option label="条状固态" value="条状固态" />
                  <el-option label="块状固态" value="块状固态" />
                  <el-option label="气态" value="气态" />
                  <el-option label="液态" value="液态" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" width="180">
              <template #header>
                <el-tooltip
                  content="需要定性分析请填写定性或者二氧化硅"
                  effect="light"
                  placement="top"
                >
                  <span style="display: inline-flex; align-items: center">
                    主要成分
                    <span class="required-star">*</span>
                       <el-tooltip content="列向下复制" placement="top">
                    <el-button
                      link
                      class="copy-down-btn"
                      :icon="Brush"
                      @click.stop="confirmCopyDown(materialsList, 'ingredient')"
                    />
                  </el-tooltip>
                  </span>
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-input
                  v-model="scope.row.ingredient"
                  placeholder="需要定性分析请填写定性或者二氧化硅"
                />
              </template>
            </el-table-column>
            <el-table-column align="center" width="300">
              <template #header>
                <span>生产车间/岗位/地点</span>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.workshop"
                  allow-create
                  filterable
                  placeholder="请选择生产车间/岗位/地点"
                  style="width: 100%"
                  @visible-change="(v: boolean) => v && ensureWorkshopOptions(1)"
                  @change="handleWorkshopChange"
                >
                  <el-option
                    v-for="workshop in workshopOptions"
                    :key="workshop"
                    :label="workshop"
                    :value="workshop"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template #default="scope">
                <el-button link type="primary" @click="handleMaterialCopy(scope.$index)"
                  >复制
                </el-button>
                <el-button link type="danger" @click="handleMaterialDelete(scope.$index)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 新增原辅材料弹窗 -->
          <el-dialog
            v-model="materialDialogVisible"
            :close-on-click-modal="false"
            title="新增原辅材料"
            width="1200px"
          >
            <div class="mb-4">
              <el-button type="primary" @click="addMaterialRow">新增</el-button>
            </div>

            <el-table :data="materialFormList" border style="width: 100%">
              <el-table-column align="center" label="序号" type="index" width="60" />

              <el-table-column label="辅料名称" width="150">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.materialName"
                    placeholder="请输入辅料名称"
                    size="small"
                  />
                </template>
              </el-table-column>

              <el-table-column label="用量" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.usage" placeholder="请输入用量" size="small" />
                </template>
              </el-table-column>

              <el-table-column label="物理状态" width="120">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.physicalState"
                    placeholder="请输入物理状态"
                    size="small"
                  filterable
                  allow-create
                  style="width: 100%"
                  >
                    <el-option label="固态" value="固态" />
                    <el-option label="粉状固态" value="粉状固态" />
                    <el-option label="粒状固态" value="粒状固态" />
                    <el-option label="片状固态" value="片状固态" />
                    <el-option label="条状固态" value="条状固态" />
                    <el-option label="块状固态" value="块状固态" />
                    <el-option label="气态" value="气态" />
                    <el-option label="液态" value="液态" />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="主要成分" width="150">
                <template #header>
                  <el-tooltip
                    content="需要定性分析请填写定性或者二氧化硅"
                    effect="light"
                    placement="top"
                  >
                    <span style="display: inline-flex; align-items: center"> 主要成分 </span>
                  </el-tooltip>
                </template>
                <template #default="scope">
                  <el-input
                    v-model="scope.row.ingredient"
                    placeholder="需要定性分析请填写定性或者二氧化硅"
                    size="small"
                  />
                </template>
              </el-table-column>

              <el-table-column label="生产车间/岗位/地点" min-width="300">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.workshops"
                    allow-create
                    filterable
                    multiple
                    placeholder="请选择地点"
                    size="small"
                    style="width: 100%"
                    @visible-change="(v: boolean) => v && ensureWorkshopOptions(1)"
                    @change="handleWorkshopChange"
                  >
                    <el-option
                      v-for="workshop in workshopOptions"
                      :key="workshop"
                      :label="workshop"
                      :value="workshop"
                    />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column align="center" label="操作" width="100">
                <template #default="scope">
                  <el-button
                    :disabled="materialFormList.length <= 1"
                    link
                    size="small"
                    type="danger"
                    @click="removeMaterialRow(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <template #footer>
              <span class="dialog-footer">
                <el-button @click="handleMaterialCancel">取消</el-button>
                <el-button type="primary" @click="handleMaterialConfirm">确认添加</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </el-tab-pane>
      <el-tab-pane label="中间产物" name="intermediate">
        <div class="equipment-content">
          <!-- 添加新增按钮 -->
          <div class="mb-4">
            <el-button type="primary" @click="handleAddIntermediate">新增中间产物</el-button>
          </div>
          <el-table :data="intermediateList" :span-method="intermediateSpanMethod" border>
            <el-table-column align="center" width="400">
              <template #header>
                <span>中间产物、副产品、联产产品名称</span>
                <span class="required-star">*</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(materialsList, 'intermediateName')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.intermediateName" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="180">
              <template #header>
                <span>产量/产值</span>
                <span class="required-star">*</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(materialsList, 'production')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.production" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="200">
              <template #header>
                <span>主要成分</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(intermediateList, 'ingredient')"
                  />
                </el-tooltip>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.ingredient" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="180">
              <template #header>
                <span>物理状态</span>
                <span class="required-star">*</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(materialsList, 'physicalState')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.physicalState"
                  placeholder="请选择物理状态"
                  filterable
                  allow-create
                  style="width: 100%"
                >
                  <el-option label="固态" value="固态" />
                  <el-option label="粉状固态" value="粉状固态" />
                  <el-option label="粒状固态" value="粒状固态" />
                  <el-option label="片状固态" value="片状固态" />
                  <el-option label="条状固态" value="条状固态" />
                  <el-option label="块状固态" value="块状固态" />
                  <el-option label="气态" value="气态" />
                  <el-option label="液态" value="液态" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" width="180">
              <template #header>
                <span>包装方式</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(intermediateList, 'packaging')"
                  />
                </el-tooltip>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.packaging" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="300">
              <template #header>
                <span>生产车间/岗位/地点</span>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.workshop"
                  allow-create
                  filterable
                  placeholder="请选择或输入生产车间/岗位/地点"
                  style="width: 100%"
                  @visible-change="(v: boolean) => v && ensureWorkshopOptions(2)"
                  @change="handleWorkshopChange"
                >
                  <el-option
                    v-for="workshop in workshopOptions"
                    :key="workshop"
                    :label="workshop"
                    :value="workshop"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template #default="scope">
                <el-button link type="primary" @click="handleIntermediateCopy(scope.$index)"
                  >复制
                </el-button>
                <el-button link type="danger" @click="handleIntermediateDelete(scope.$index)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 新增中间产物弹窗 -->
          <el-dialog
            v-model="intermediateDialogVisible"
            :close-on-click-modal="false"
            title="新增中间产物"
            width="1300px"
          >
            <div class="mb-4">
              <el-button type="primary" @click="addIntermediateRow">新增</el-button>
            </div>

            <el-table :data="intermediateFormList" border style="width: 100%">
              <el-table-column align="center" label="序号" type="index" width="60" />

              <el-table-column label="中间产物、副产品、联产产品名称" width="250">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.intermediateName"
                    placeholder="请输入中间产物名称"
                    size="small"
                  />
                </template>
              </el-table-column>

              <el-table-column label="产量/产值" width="150">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.production"
                    placeholder="请输入产量/产值"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="主要成分" width="180">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.ingredient"
                    placeholder="请输入主要成分"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="物理状态" width="150">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.physicalState"
                    placeholder="请选择物理状态"
                    filterable
                    allow-create
                    style="width: 100%"
                  >
                    <el-option label="固态" value="固态" />
                    <el-option label="粉状固态" value="粉状固态" />
                    <el-option label="粒状固态" value="粒状固态" />
                    <el-option label="片状固态" value="片状固态" />
                    <el-option label="条状固态" value="条状固态" />
                    <el-option label="块状固态" value="块状固态" />
                    <el-option label="气态" value="气态" />
                    <el-option label="液态" value="液态" />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="包装方式" width="150">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.packaging"
                    placeholder="请输入包装方式"
                    size="small"
                  />
                </template>
              </el-table-column>

              <el-table-column label="生产车间/岗位/地点" min-width="300">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.workshops"
                    allow-create
                    filterable
                    multiple
                    placeholder="请选择或输入地点"
                    size="small"
                    style="width: 100%"
                    @visible-change="(v: boolean) => v && ensureWorkshopOptions(1)"
                    @change="handleWorkshopChange"
                  >
                    <el-option
                      v-for="workshop in workshopOptions"
                      :key="workshop"
                      :label="workshop"
                      :value="workshop"
                    />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column align="center" label="操作" width="100">
                <template #default="scope">
                  <el-button
                    :disabled="intermediateFormList.length <= 1"
                    size="small"
                    type="danger"
                    @click="removeIntermediateRow(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <template #footer>
              <span class="dialog-footer">
                <el-button @click="handleIntermediateCancel">取消</el-button>
                <el-button type="primary" @click="handleIntermediateConfirm">确认添加</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </el-tab-pane>
      <el-tab-pane label="主要产品" name="products">
        <div class="equipment-content">
          <!-- 添加新增按钮 -->
          <div class="mb-4">
            <el-button type="primary" @click="handleAddProduct">新增主要产品</el-button>
          </div>
            <el-table :data="productsList" border>
            <el-table-column align="center" width="300">
              <template #header>
                <span>产品名称</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(productsList, 'productName')"
                  />
                </el-tooltip>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.productName" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="180">
              <template #header>
                <span>产量/产值</span>
                <span class="required-star">*</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(intermediateList, 'production')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.production" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="180">
              <template #header>
                <span>物理状态</span>
                <span class="required-star">*</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(intermediateList, 'physicalState')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.physicalState"
                  placeholder="请选择物理状态"
                  filterable
                  allow-create
                  style="width: 100%"
                >
                  <el-option label="固态" value="固态" />
                  <el-option label="粉状固态" value="粉状固态" />
                  <el-option label="粒状固态" value="粒状固态" />
                  <el-option label="片状固态" value="片状固态" />
                  <el-option label="条状固态" value="条状固态" />
                  <el-option label="块状固态" value="块状固态" />
                  <el-option label="气态" value="气态" />
                  <el-option label="液态" value="液态" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" width="180">
              <template #header>
                <span>包装方式</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(productsList, 'packaging')"
                  />
                </el-tooltip>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.packaging" />
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template #default="scope">
                <el-button link type="primary" @click="handleProductCopy(scope.$index)"
                  >复制
                </el-button>
                <el-button link type="danger" @click="handleProductDelete(scope.$index)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="主要设备" name="equipment">
        <div class="equipment-content">
          <!-- 添加新增按钮 -->
          <div class="mb-4">
            <el-button type="primary" @click="handleAddEquipment">新增设备</el-button>
          </div>
          <el-table :data="equipmentList" :span-method="equipmentSpanMethod" border>
            <el-table-column align="center" width="400">
              <template #header>
                <span>设备名称</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(equipmentList, 'equipmentName')"
                  />
                </el-tooltip>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.equipmentName" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="200">
              <template #header>
                <span>数量(台/套)</span>
                <span class="required-star">*</span>
              </template>
              <el-table-column align="center" width="100">
                <template #header>
                  <span>总数</span>
                  <el-tooltip content="列向下复制" placement="top">
                    <el-button
                      link
                      class="copy-down-btn"
                      :icon="Brush"
                      @click.stop="confirmCopyDown(equipmentList, 'quantity')"
                    />
                  </el-tooltip>
                </template>
                <template #default="scope">
                  <el-input v-model="scope.row.quantity" type="number" />
                </template>
              </el-table-column>
              <el-table-column align="center" width="100">
                <template #header>
                  <span>运行</span>
                  <el-tooltip content="列向下复制" placement="top">
                    <el-button
                      link
                      class="copy-down-btn"
                      :icon="Brush"
                      @click.stop="confirmCopyDown(equipmentList, 'runningQuantity')"
                    />
                  </el-tooltip>
                </template>
                <template #default="scope">
                  <el-input v-model="scope.row.runningQuantity" type="number" />
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column align="center" width="180">
              <template #header>
                <span>规格型号</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(equipmentList, 'specification')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.specification" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="200">
              <template #header>
                <span>设备布局</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(equipmentList, 'equipmentLayout')"
                  />
                </el-tooltip>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.equipmentLayout"
                  multiple
                  allow-create
                  filterable
                  placeholder="请选择设备布局"
                  style="width: 100%"
                >
                  <el-option label="机群式布局" value="机群式布局" />
                  <el-option label="U型生产线布局" value="U型生产线布局" />
                  <el-option label="直线型生产线布局" value="直线型生产线布局" />
                  <el-option label="Y型生产线布局" value="Y型生产线布局" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" width="300">
              <template #header>
                <span>生产车间/岗位</span>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.workshop"
                  allow-create
                  filterable
                  placeholder="请选择或输入生产车间/岗位/地点"
                  style="width: 100%"
                  @visible-change="(v: boolean) => v && ensureWorkshopOptions(2)"
                  @change="handleWorkshopChange"
                >
                  <el-option
                    v-for="workshop in workshopOptions"
                    :key="workshop"
                    :label="workshop"
                    :value="workshop"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template #default="scope">
                <el-button link type="primary" @click="handleEquipmentCopy(scope.$index)"
                  >复制
                </el-button>
                <el-button link type="danger" @click="handleDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 新增设备弹窗 -->
          <el-dialog
            v-model="equipmentDialogVisible"
            :close-on-click-modal="false"
            title="新增设备"
            width="1200px"
          >
            <div class="mb-4">
              <el-button type="primary" @click="addEquipmentRow">新增</el-button>
            </div>

            <el-table :data="equipmentFormList" border style="width: 100%">
              <el-table-column align="center" label="序号" type="index" width="60" />

              <el-table-column label="设备名称" width="200">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.equipmentName"
                    placeholder="请输入设备名称"
                    size="small"
                  />
                </template>
              </el-table-column>

              <el-table-column label="数量(台/套)" width="200">
                <el-table-column label="总数" width="100">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.quantity"
                      placeholder="总数"
                      size="small"
                      type="number"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="运行" width="100">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.runningQuantity"
                      placeholder="运行"
                      size="small"
                      type="number"
                    />
                  </template>
                </el-table-column>
              </el-table-column>

              <el-table-column label="规格型号" width="150">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.specification"
                    placeholder="请输入规格型号"
                    size="small"
                  />
                </template>
              </el-table-column>

              <el-table-column label="设备布局" width="150">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.equipmentLayout"
                    allow-create
                    filterable
                    placeholder="请选择设备布局"
                    size="small"
                    style="width: 100%"
                  >
                    <el-option label="机群式布局" value="机群式布局" />
                    <el-option label="U型生产线布局" value="U型生产线布局" />
                    <el-option label="直线型生产线布局" value="直线型生产线布局" />
                    <el-option label="Y型生产线布局" value="Y型生产线布局" />
                    <el-option label="其他" value="其他" />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="生产车间/岗位" min-width="200">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.workshops"
                    allow-create
                    filterable
                    multiple
                    placeholder="请选择或输入地点"
                    size="small"
                    style="width: 100%"
                    @visible-change="(v: boolean) => v && ensureWorkshopOptions(2)"
                    @change="handleWorkshopChange"
                  >
                    <el-option
                      v-for="workshop in workshopOptions"
                      :key="workshop"
                      :label="workshop"
                      :value="workshop"
                    />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column align="center" label="操作" width="100">
                <template #default="scope">
                  <el-button
                    :disabled="equipmentFormList.length <= 1"
                    size="small"
                    type="danger"
                    @click="removeEquipmentRow(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <template #footer>
              <span class="dialog-footer">
                <el-button @click="handleEquipmentCancel">取消</el-button>
                <el-button type="primary" @click="handleEquipmentConfirm">确认添加</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </el-tab-pane>
      <el-tab-pane label="防护设施" name="facilities">
        <div class="equipment-content">
          <!-- 添加新增按钮 -->
          <div class="mb-4">
            <el-button type="primary" @click="handleAddFacility">新增防护设施</el-button>
          </div>
          <el-table :data="facilitiesList" :span-method="facilitiesSpanMethod" border>
            <el-table-column align="center" width="400">
              <template #header>
                <span>防护设施名称</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(facilitiesList, 'facilityName')"
                  />
                </el-tooltip>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.facilityName" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="250">
              <template #header>
                <span>防护设施类型</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(facilitiesList, 'facilityType')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.facilityType"
                  placeholder="请选择防护设施类型"
                  multiple
                  allow-create
                  filterable
                  style="width: 100%"
                >
                  <el-option label="防毒" value="防毒" />
                  <el-option label="防尘" value="防尘" />
                  <el-option label="防噪" value="防噪" />
                  <el-option label="减振" value="减振" />
                  <el-option label="防暑降温" value="防暑降温" />
                  <el-option label="防低温" value="防低温" />
                  <el-option label="防非电磁辐射" value="防非电磁辐射" />
                  <el-option label="防电离辐射" value="防电离辐射" />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column align="center" width="200">
              <template #header>
                <span>数量(台/套)</span>
              </template>
              <el-table-column align="center" width="100">
                <template #header>
                  <span>总数</span>
                    <el-tooltip content="列向下复制" placement="top">
                      <el-button
                        link
                        class="copy-down-btn"
                        :icon="Brush"
                        @click.stop="confirmCopyDown(facilitiesList, 'total')"
                      />
                    </el-tooltip>
                </template>
                <template #default="scope">
                  <el-input v-model="scope.row.total" type="number" />
                </template>
              </el-table-column>
              <el-table-column align="center" width="100">
                <template #header>
                  <span>运行数</span>
                  <el-tooltip content="列向下复制" placement="top">
                    <el-button
                      link
                      class="copy-down-btn"
                      :icon="Brush"
                      @click.stop="confirmCopyDown(facilitiesList, 'running')"
                    />
                  </el-tooltip>
                </template>
                <template #default="scope">
                  <el-input v-model="scope.row.running" type="number" />
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column align="center" width="300">
              <template #header>
                <span>生产车间/岗位/地点</span>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.workshop"
                  allow-create
                  filterable
                  placeholder="请选择或输入生产车间/岗位"
                  style="width: 100%"
                  @visible-change="(v: boolean) => v && ensureWorkshopOptions(1)"
                  @change="handleWorkshopChange"
                >
                  <el-option
                    v-for="workshop in workshopOptions"
                    :key="workshop"
                    :label="workshop"
                    :value="workshop"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template #default="scope">
                <el-button link type="primary" @click="handleFacilityCopy(scope.$index)"
                  >复制
                </el-button>
                <el-button link type="danger" @click="handleFacilityDelete(scope.$index)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 新增防护设施弹窗 -->
          <el-dialog
            v-model="facilitiesDialogVisible"
            :close-on-click-modal="false"
            title="新增防护设施"
            width="1100px"
          >
            <div class="mb-4">
              <el-button type="primary" @click="addFacilitiesRow">新增</el-button>
            </div>

            <el-table :data="facilitiesFormList" border style="width: 100%">
              <el-table-column align="center" label="序号" type="index" width="60" />
              <el-table-column label="防护设施名称" width="200">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.facilityName"
                    placeholder="请输入防护设施名称"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="防护设施类型" width="250">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.facilityType"
                    placeholder="请选择防护设施类型"
                    multiple
                    allow-create
                    filterable
                    size="small"
                    style="width: 100%"
                  >
                    <el-option label="防毒" value="防毒" />
                    <el-option label="防尘" value="防尘" />
                    <el-option label="防噪" value="防噪" />
                    <el-option label="减振" value="减振" />
                    <el-option label="防暑降温" value="防暑降温" />
                    <el-option label="防低温" value="防低温" />
                    <el-option label="防非电磁辐射" value="防非电磁辐射" />
                    <el-option label="防电离辐射" value="防电离辐射" />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="数量(台/套)" width="300">
                <el-table-column label="总数" width="130">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.total"
                      placeholder="请输入总数"
                      size="small"
                      type="number"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="运行数" width="130">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.running"
                      placeholder="请输入运行数"
                      size="small"
                      type="number"
                    />
                  </template>
                </el-table-column>
              </el-table-column>

              <el-table-column label="生产车间/岗位/地点" min-width="200">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.workshops"
                    allow-create
                    filterable
                    multiple
                    placeholder="请选择或输入地点"
                    size="small"
                    style="width: 100%"
                    @visible-change="(v: boolean) => v && ensureWorkshopOptions(1)"
                    @change="handleWorkshopChange"
                  >
                    <el-option
                      v-for="workshop in workshopOptions"
                      :key="workshop"
                      :label="workshop"
                      :value="workshop"
                    />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column align="center" label="操作" width="100">
                <template #default="scope">
                  <el-button
                    :disabled="facilitiesFormList.length <= 1"
                    size="small"
                    type="danger"
                    @click="removeFacilitiesRow(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <template #footer>
              <span class="dialog-footer">
                <el-button @click="handleFacilitiesCancel">取消</el-button>
                <el-button type="primary" @click="handleFacilitiesConfirm">确认添加</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </el-tab-pane>
      <el-tab-pane label="个人防护" name="protection">
        <div class="equipment-content">
          <!-- 添加新增按钮 -->
          <div class="mb-4">
            <el-button type="primary" @click="handleAddProtection">新增防护用品</el-button>
          </div>
          <el-table :data="protectionList" :span-method="protectionSpanMethod" border>
            <el-table-column align="center" width="300">
              <template #header>
                <span>职业病防护用品分类</span>
                <span class="required-star">*</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(protectionList, 'protectionName')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.protectionName"
                  placeholder="请选择防护用品名称"
                  style="width: 100%"
                  filterable
                  allow-create
                >
                  <el-option label="眼面防护" value="眼面防护" />
                  <el-option label="听力防护" value="听力防护" />
                  <el-option label="呼吸防护" value="呼吸防护" />
                  <el-option label="防护服装" value="防护服装" />
                  <el-option label="手部防护" value="手部防护" />
                  <el-option label="足部防护" value="足部防护" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" width="210">
              <template #header>
                <span>职业病防护用品类别</span>
                <span class="required-star">*</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(protectionList, 'protectionType')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.protectionType"
                  placeholder="请选择防护用品类别"
                  style="width: 100%"
                  filterable
                  allow-create
                >
                  <el-option label="耳塞" value="耳塞" />
                  <el-option label="耳罩" value="耳罩" />
                  <el-option label="防尘口罩" value="防尘口罩" />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column align="center" width="180">
              <template #header>
                <span>生产厂家</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(protectionList, 'manufacturer')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.manufacturer" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="180">
              <template #header>
                <span>型号、参数</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(protectionList, 'specification')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.specification" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="180">
              <template #header>
                <span>更换周期</span>
                <el-tooltip content="列向下复制" placement="top">
                  <el-button
                    link
                    class="copy-down-btn"
                    :icon="Brush"
                    @click.stop="confirmCopyDown(protectionList, 'replacementCycle')"
                  />
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-input v-model="scope.row.replacementCycle" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="300">
              <template #header>
                <span>生产车间/岗位/地点</span>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.workshop"
                  allow-create
                  filterable
                  placeholder="请选择或输入生产车间/岗位/地点"
                  style="width: 100%"
                  @change="handleWorkshopChange"
                >
                  <el-option
                    v-for="workshop in workshopOptions"
                    :key="workshop"
                    :label="workshop"
                    :value="workshop"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template #default="scope">
                <el-button link type="primary" @click="handleProtectionCopy(scope.$index)"
                  >复制
                </el-button>
                <el-button link type="danger" @click="handleProtectionDelete(scope.$index)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 新增个人防护用品弹窗 -->
          <el-dialog
            v-model="protectionDialogVisible"
            :close-on-click-modal="false"
            title="新增个人防护用品"
            width="1200px"
          >
            <div class="mb-4">
              <el-button type="primary" @click="addProtectionRow">新增</el-button>
            </div>

            <el-table :data="protectionFormList" border style="width: 100%">
              <el-table-column align="center" label="序号" type="index" width="60" />
              <el-table-column label="职业病防护用品分类" width="200">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.protectionName"
                    placeholder="请选择防护用品名称"
                    size="small"
                    style="width: 100%"
                    filterable
                    allow-create
                  >
                    <el-option label="呼吸" value="呼吸" />
                    <el-option label="眼部" value="眼部" />
                    <el-option label="面部" value="面部" />
                    <el-option label="头部" value="头部" />
                    <el-option label="眼面部" value="眼面部" />
                    <el-option label="听觉" value="听觉" />
                    <el-option label="手部" value="手部" />
                    <el-option label="足部" value="足部" />
                    <el-option label="皮肤" value="皮肤" />
                    <el-option label="防静电" value="防静电" />
                    <el-option label="躯干" value="躯干" />
                    <el-option label="全身" value="全身" />
                    <el-option label="听力防护" value="听力防护" />
                    <el-option label="防护服装" value="防护服装" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="职业病防护用品类别" width="180">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.protectionType"
                    placeholder="请选择防护用品类别"
                    size="small"
                    style="width: 100%"
                    filterable
                    allow-create
                  >
                    <el-option label="耳塞" value="耳塞" />
                    <el-option label="耳罩" value="耳罩" />
                    <el-option label="防尘口罩" value="防尘口罩" />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="生产厂家" width="150">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.manufacturer"
                    placeholder="请输入生产厂家"
                    size="small"
                  />
                </template>
              </el-table-column>

              <el-table-column label="型号、参数" width="150">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.specification"
                    placeholder="请输入型号、参数"
                    size="small"
                  />
                </template>
              </el-table-column>

              <el-table-column label="更换周期" width="120">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.replacementCycle"
                    placeholder="请输入更换周期"
                    size="small"
                  />
                </template>
              </el-table-column>

              <el-table-column label="生产车间/岗位" min-width="200">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.workshops"
                    allow-create
                    filterable
                    multiple
                    placeholder="请选择或输入地点"
                    size="small"
                    style="width: 100%"
                    @change="handleWorkshopChange"
                    @visible-change="(v: boolean) => v && ensureWorkshopOptions(2)"
                  >
                    <el-option
                      v-for="workshop in workshopOptions"
                      :key="workshop"
                      :label="workshop"
                      :value="workshop"
                    />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column align="center" label="操作" width="100">
                <template #default="scope">
                  <el-button
                    :disabled="protectionFormList.length <= 1"
                    size="small"
                    type="danger"
                    @click="removeProtectionRow(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <template #footer>
              <span class="dialog-footer">
                <el-button @click="handleProtectionCancel">取消</el-button>
                <el-button type="primary" @click="handleProtectionConfirm">确认添加</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </el-tab-pane>
      <el-tab-pane label="工艺流程" name="process">
        <div class="equipment-content">
          <div class="mb-4">
            <el-button type="primary" @click="handleAddProcess">新增工艺流程</el-button>
          </div>
          <el-table :data="processList" border>
            <el-table-column align="center" width="450">
              <template #header>
                <span>工艺名称</span>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-input
                  v-model="scope.row.processName"
                  :rows="7"
                  placeholder="请输入工艺名称"
                  type="textarea"
                />
              </template>
            </el-table-column>
            <el-table-column align="center" width="450">
              <template #header>
                <span>流程图</span>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <div class="image-upload-container">
                  <el-upload
                    :auto-upload="false"
                    :on-change="(file) => handleProcessImageUpload(file.raw!, scope.$index)"
                    :show-file-list="false"
                    accept="image/*"
                    class="image-uploader"
                    multiple
                  >
                    <el-button type="primary">上传图片</el-button>
                  </el-upload>
                  <div class="image-list">
                    <div
                      v-for="(image, imageIndex) in scope.row.processImages"
                      :key="imageIndex"
                      class="image-item"
                    >
                      <el-image
                        :initial-index="imageIndex"
                        :preview-src-list="scope.row.processImages"
                        :src="image"
                        class="preview-image"
                        fit="cover"
                        hide-on-click-modal
                        preview-teleported
                      />
                      <el-button
                        class="delete-button"
                        size="small"
                        type="danger"
                        @click="handleProcessImageRemove(scope.$index, imageIndex)"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" width="600">
              <template #header>
                <span>过程描述</span>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-input
                  v-model="scope.row.processDescription"
                  :rows="7"
                  placeholder="请输入过程描述"
                  type="textarea"
                />
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template #default="scope">
                <el-button link type="danger" @click="handleProcessDelete(scope.$index)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="平面布局" name="layout">
        <div class="equipment-content">
          <div class="mb-4">
            <el-button type="primary" @click="handleAddLayout">新增平面布局</el-button>
          </div>
          <el-table :data="layoutList" border>
            <el-table-column align="center" width="450">
              <template #header>
                <span>平面布局图</span>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <div class="image-upload-container">
                  <el-upload
                    :auto-upload="false"
                    :on-change="(file) => handleLayoutImageUpload(file.raw!, scope.$index)"
                    :show-file-list="false"
                    accept="image/*"
                    class="image-uploader"
                    multiple
                  >
                    <el-button type="primary">上传图片</el-button>
                  </el-upload>
                  <div class="image-list">
                    <div
                      v-for="(image, imageIndex) in scope.row.layoutImages"
                      :key="imageIndex"
                      class="image-item"
                    >
                      <el-image
                        :initial-index="imageIndex"
                        :preview-src-list="scope.row.layoutImages"
                        :src="image"
                        class="preview-image"
                        fit="cover"
                        hide-on-click-modal
                        preview-teleported
                      />
                      <el-button
                        class="delete-button"
                        size="small"
                        type="danger"
                        @click="handleLayoutImageRemove(scope.$index, imageIndex)"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template #default="scope">
                <el-button link type="danger" @click="handleLayoutDelete(scope.$index)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="设备布局" name="equipment-layout">
        <div class="equipment-content">
          <div class="mb-4">
            <el-button type="primary" @click="handleAddEquipmentLayout">新增设备布局</el-button>
          </div>
          <el-table :data="equipmentLayoutList" border>
            <el-table-column align="center" width="250">
              <template #header>
                <span>工作场所</span>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.workplace"
                  allow-create
                  filterable
                  multiple
                  placeholder="请选择或输入工作场所"
                  style="width: 100%"
                  @visible-change="(v: boolean) => v && ensureWorkshopOptions(3)"
                  @change="handleWorkshopChange"
                >
                  <el-option
                    v-for="workshop in workshopOptions"
                    :key="workshop"
                    :label="workshop"
                    :value="workshop"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" width="450">
              <template #header>
                <span>设备布局图</span>
                <span class="required-star">*</span>
              </template>
              <template #default="scope">
                <div class="image-upload-container">
                  <el-upload
                    :auto-upload="false"
                    :on-change="(file) => handleEquipmentLayoutImageUpload(file.raw!, scope.$index)"
                    :show-file-list="false"
                    accept="image/*"
                    class="image-uploader"
                    multiple
                  >
                    <el-button type="primary">上传图片</el-button>
                  </el-upload>
                  <div class="image-list">
                    <div
                      v-for="(image, imageIndex) in scope.row.layoutImages"
                      :key="imageIndex"
                      class="image-item"
                    >
                      <el-image
                        :initial-index="imageIndex"
                        :preview-src-list="scope.row.layoutImages"
                        :src="image"
                        class="preview-image"
                        fit="cover"
                        hide-on-click-modal
                        preview-teleported
                      />
                      <el-button
                        class="delete-button"
                        size="small"
                        type="danger"
                        @click="handleEquipmentLayoutImageRemove(scope.$index, imageIndex)"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template #default="scope">
                <el-button link type="danger" @click="handleEquipmentLayoutDelete(scope.$index)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 引入签名组件 -->
    <Signature ref="signatureRef" :projectId="`${route.query.projectId}`" :reportType="'AAAB'" />

    <!-- 同步定性结果弹窗 -->
    <SyncResultsDialog
      v-model="syncResultsDialogVisible"
      :project-id="route.query.projectId as string"
      :job-survey-ref="jobSurveyRef"
      @sync-completed="handleSyncCompleted"
    />

    <el-dialog v-model="dialogVisible"   width="500px">
      <div style="margin-bottom: 20px;">
        <h4>上标数字：</h4>
        <p style="font-size: 28px; font-family: monospace;">
          x&#8304; x&#185; x&#178; x&#179; x&#8308; x&#8309; x&#8310; x&#8311; x&#8312; x&#8313;
        </p>
      </div>

      <div>
        <h4>下标数字：</h4>
        <p style="font-size: 28px; font-family: monospace;">
          x&#8320; x&#8321; x&#8322; x&#8323; x&#8324; x&#8325; x&#8326; x&#8327; x&#8328; x&#8329;
        </p>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, reactive, ref, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ProjectApi } from '@/api/dk/project'
import JobSurvey from './JobSurvey.vue'
import Signature from '@/views/project/list/Signature.vue'
import SyncResultsDialog from './SyncResultsDialog.vue'
import { useUpload } from '@/components/UploadFile/src/useUpload'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Brush } from '@element-plus/icons-vue'
import type { UploadRawFile } from 'element-plus/es/components/upload/src/upload'

const route = useRoute()
const router = useRouter()
const operationType = ref(1)
const { httpRequest } = useUpload()
const signatureRef = ref()
const jobSurveyRef = ref()
const formRef = ref()
// 是否存在可同步的定性结果
const hasUnknownResults = ref(false)
// 当前激活的标签页
const activeTab = ref('basic')
// 同步定性结果弹窗
const syncResultsDialogVisible = ref(false)
// 添加初始化状态标志
const isInitializing = ref(true)
// 添加用户操作标志，用于区分是用户操作还是初始化
const isUserAction = ref(false)
const dialogVisible = ref(false)

// 监听标签页切换
watch(activeTab, (newTab) => {
  // 将当前选中的 tab 保存到 localStorage
  localStorage.setItem('fieldSurveyActiveTab', newTab)

  // 切换tab仅切换到缓存数据，不触发接口调用
  let targetType = 1
  if (newTab === 'materials' || newTab === 'intermediate' || newTab === 'facilities') {
    targetType = 1 // 原辅材料、中间产物、防护设施使用 type=1
  } else if (newTab === 'equipment' || newTab === 'protection') {
    targetType = 2 // 主要设备、个人防护使用 type=2
  } else if (newTab === 'equipment-layout') {
    targetType = 3 // 设备布局使用 type=3
  }

  if (workshopOptionsCache.value[targetType] && workshopOptionsCache.value[targetType].length) {
    workshopOptions.value = Array.from(new Set(workshopOptionsCache.value[targetType]))
  } else {
    workshopOptions.value = []
  }
})

// 扩展表单数据接口
interface FormData {
  entrustCompany: string
  inspectedCompany: string
  creditCode: string
  legalPerson: string
  registeredAddress: string
  workplaceAddress: string
  productionDate: string
  companyNature: string
  email: string
  totalEmployees: string
  dispatchedWorkers: string
  companySize: string
  industry: string
  healthManager: string
  riskLevel: string
  surveyRemarks: string
  projectId: string | undefined
  projectNo: string | undefined
  contactPerson: string
  contactPhone: string
  contactEmail: string
}

// 表单数据
const formData = reactive<FormData>({
  entrustCompany: '',
  inspectedCompany: '',
  creditCode: '',
  legalPerson: '',
  companySize: '',
  registeredAddress: '',
  workplaceAddress: '',
  productionDate: '',
  companyNature: '',
  email: '',
  totalEmployees: '',
  dispatchedWorkers: '',
  industry: '',
  healthManager: '',
  riskLevel: '',
  surveyRemarks: '',
  projectId: undefined,
  projectNo: undefined,
  contactPerson: '',
  contactPhone: '',
  contactEmail: ''
})

// 技术服务地址（多项）
const workplaceAddresses = ref<string[]>([''])

// 初始化/同步多地址与单字段
watch(
  () => formData.workplaceAddress,
  (val) => {
    // 将后端保存的分隔字符串切分为数组；使用中文逗号或英文逗号分隔
    if (typeof val === 'string') {
      const parts = val
        .split(/[,]/)
        .map((s) => s.trim())
        .filter((s) => s.length > 0)
      workplaceAddresses.value = parts.length ? parts : ['']
    }
  },
  { immediate: true }
)

// 在保存时把数组合并回单字段（使用中文顿号分隔）
const syncWorkplaceAddressForSave = () => {
  const merged = workplaceAddresses.value
    .map((s) => s.trim())
    .filter((s) => s.length > 0)
    .join(',')
  formData.workplaceAddress = merged
}

// 投产时间精度：年/年月/年月日
const productionDateMode = ref<'year' | 'month' | 'date'>('date')
const productionPickerType = computed(() =>
  productionDateMode.value === 'year' ? 'year' : productionDateMode.value === 'month' ? 'month' : 'date'
)
const productionValueFormat = computed(() =>
  productionDateMode.value === 'year' ? 'YYYY' : productionDateMode.value === 'month' ? 'YYYY-MM' : 'YYYY-MM-DD'
)
const productionDisplayFormat = productionValueFormat

const syncProductionModeFromValue = (val?: string) => {
  const v = (val ?? formData.productionDate)?.trim()
  if (!v) return
  if (/^\d{4}$/.test(v)) {
    productionDateMode.value = 'year'
  } else if (/^\d{4}-\d{2}$/.test(v)) {
    productionDateMode.value = 'month'
  } else {
    productionDateMode.value = 'date'
  }
}

watch(
  () => formData.productionDate,
  (v) => {
    syncProductionModeFromValue(v)
  },
  { immediate: true }
)

watch(productionDateMode, (mode) => {
  const v = formData.productionDate?.trim()
  if (!v) return
  if (mode === 'year') {
    formData.productionDate = v.slice(0, 4)
  } else if (mode === 'month') {
    if (/^\d{4}$/.test(v)) {
      formData.productionDate = `${v}-01`
    } else {
      formData.productionDate = v.slice(0, 7)
    }
  } else if (mode === 'date') {
    if (/^\d{4}$/.test(v)) {
      formData.productionDate = `${v}-01-01`
    } else if (/^\d{4}-\d{2}$/.test(v)) {
      formData.productionDate = `${v}-01`
    }
  }
})

// 表单验证规则
const formRules = reactive({
  creditCode: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (!value) {
          callback()
          return
        }
        // 社会信用代码格式验证：18位，前2位为字母，后16位为数字或字母
        const creditCodePattern = /^[A-Z0-9]{2}[A-Z0-9]{16}$/
        if (!creditCodePattern.test(value.toUpperCase())) {
          callback(new Error('社会信用代码格式不正确，应为18位字母数字组合'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  totalEmployees: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (!value) {
          callback()
          return
        }
        const num = parseInt(value)
        if (isNaN(num) || num <= 0 || !Number.isInteger(num)) {
          callback(new Error('在册职工总人数必须为正整数'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  dispatchedWorkers: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (!value) {
          callback()
          return
        }
        const num = parseInt(value)
        if (isNaN(num) || num < 0 || !Number.isInteger(num)) {
          callback(new Error('劳务派遣人员必须为非负整数'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  contactEmail: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (!value) {
          callback()
          return
        }
        // 邮箱格式验证
        const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
        if (!emailPattern.test(value)) {
          callback(new Error('联系人邮箱格式不正确'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  contactPhone: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (!value) {
          callback()
          return
        }
        // 手机号格式验证：11位数字，以1开头
        const phonePattern = /^1[3-9]\d{9}$/
        // 固定电话格式验证：区号+号码
        const landlinePattern = /^0\d{2,3}-?\d{7,8}$/
        if (!phonePattern.test(value) && !landlinePattern.test(value)) {
          callback(new Error('联系人电话格式不正确，请输入正确的手机号或固定电话'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 设备列表数据接口
interface EquipmentItem {
  workshop: string
  equipmentName: string
  specification: string
  quantity: number | string
  runningQuantity: number | string
  equipmentLayout: string | string[]
}

// 设备列表数据
const equipmentList = ref<EquipmentItem[]>([])

// 新增设备弹窗相关数据
const equipmentDialogVisible = ref(false)
const equipmentFormList = ref([
  {
    equipmentName: '',
    quantity: '',
    runningQuantity: '',
    specification: '',
    equipmentLayout: '',
    workshops: [] as string[]
  }
])

// 原辅材料列表数据接口
interface MaterialItem {
  workshop: string // 生产车间/岗位/地点
  materialName: string
  usage: string
  physicalState: string
  ingredient: string // 主要成分字段
  remarks: string
}

// 原辅材料列表数据
const materialsList = ref<MaterialItem[]>([])

// 新增原辅材料弹窗相关数据
const materialDialogVisible = ref(false)
const materialFormList = ref([
  {
    materialName: '',
    usage: '',
    physicalState: '',
    ingredient: '',
    workshops: [] as string[]
  }
])

// 车间/岗位选项数据
const workshopOptions = ref<string[]>([])
// 缓存不同 type 的车间/岗位数据
const workshopOptionsCache = ref<{ [key: number]: string[] }>({})

// 行业相关数据
interface IndustryOption {
  id: number
  categoryName: string
  daLeiCode: string
  menLeiCode: string
  risk: string
  xiaoLeiCode: string
  zhongLeiCode: string
  description: string
}

const industryOptions = ref<IndustryOption[]>([])
const industryLoading = ref(false)
const selectedIndustryData = ref<IndustryOption | null>(null)
let searchTimeout: NodeJS.Timeout | null = null

// 企业类型相关数据
interface EnterpriseTypeOption {
  label: string
  value: string
  children?: EnterpriseTypeOption[]
}

const enterpriseTypeOptions = ref<EnterpriseTypeOption[]>([])
const enterpriseTypeLoaded = ref(false)
const expandedKeys = ref<string[]>([])

// 企业规模加载状态
const companySizeLoading = ref(false)

// 闪动效果状态
const riskLevelFlashing = ref(false)
const companySizeFlashing = ref(false)

// 主产品列表数据接口
interface ProductItem {
  productName: string
  production: string
  physicalState: string
  packaging: string
  composition: string
}

// 主产品列表数据
const productsList = ref<ProductItem[]>([])

// 中间产物列表数据接口
interface IntermediateItem {
  workshop: string
  intermediateName: string
  production: string
  physicalState: string
  ingredient: string
  packaging: string
}

// 中间产物列表数据
const intermediateList = ref<IntermediateItem[]>([])

// 新增中间产物弹窗相关数据
const intermediateDialogVisible = ref(false)
const intermediateFormList = ref([
  {
    intermediateName: '',
    production: '',
    physicalState: '',
    ingredient: '',
    packaging: '',
    workshops: [] as string[]
  }
])

// 工艺列表数据接口
interface ProcessItem {
  processName: string
  processImages: string[]
  processDescription: string
}

// 工艺列表数据
const processList = ref<ProcessItem[]>([])

// 个人防护用品列表数据接口
interface ProtectionItem {
  protectionType: string
  protectionName: string
  manufacturer: string
  specification: string
  workshop: string
  position: string
  replacementCycle: string
}

// 个人防护用品列表数据
const protectionList = ref<ProtectionItem[]>([])

// 防护设施列表数据接口
interface FacilityItem {
  workshop: string
  position: string
  facilityType: string
  facilityName: string
  total: number
  running: number
}

// 防护设施列表数据
const facilitiesList = ref<FacilityItem[]>([])

// 新增个人防护用品弹窗相关数据
const protectionDialogVisible = ref(false)
const protectionFormList = ref([
  {
    protectionType: '',
    protectionName: '',
    manufacturer: '',
    specification: '',
    replacementCycle: '',
    workshops: [] as string[]
  }
])

// 新增防护设施弹窗相关数据
const facilitiesDialogVisible = ref(false)
const facilitiesFormList = ref([
  {
    facilityType: '',
    facilityName: '',
    total: '',
    running: '',
    workshops: [] as string[]
  }
])

// 平面布局列表数据接口
interface LayoutItem {
  layoutImages: string[]
}

// 设备布局列表数据接口
interface EquipmentLayoutItem {
  workplace: string
  layoutImages: string[]
}

// 平面布局列表数据
const layoutList = ref<LayoutItem[]>([])

// 设备布局列表数据
const equipmentLayoutList = ref<EquipmentLayoutItem[]>([])

/** 添加开始调查方法 */
const toSignature = async () => {
  const { projectId } = route.query
  await ProjectApi.checkStatus(projectId, 34)
  // 调用签名组件的 showDialog 方法
  if (signatureRef.value) {
    signatureRef.value.showDialog()
  }
}

const toPreviewFieldSurvey = () => {
  // 跳转到现场调查页面，并携带项目信息
  const { projectId, projectNo } = route.query
  router.push({
    path: '/previewFile',
    query: {
      projectId: projectId,
      projectNo: projectNo,
      operationType: 1
    }
  })
}

/** 同步定性结果方法 */
const syncResults = async () => {
  const { projectId } = route.query
  await ProjectApi.checkStatus(projectId, 33)
  // 打开同步定性结果弹窗
  syncResultsDialogVisible.value = true
  console.log('syncResultsDialogVisible', syncResultsDialogVisible)
}

// 跳转到企查查搜索
const openIndustry = () => {
  const searchUrl = `https://www.guanlixi.com/hangyefenlei/`
  // const searchUrl = `https://www.mca.gov.cn/images3/www/file/201711/1509495881341.pdf`
  window.open(searchUrl, '_blank')
}
const openCompanySize = () => {
  const searchUrl = `https://cstsa.org.cn/uploads/20240617/272cc479c69c16eeaf50931127c22519.pdf`
  window.open(searchUrl, '_blank')
}
const openRiskLevel = () => {
  const searchUrl = `https://nirp.chinacdc.cn/fgbz/bmgz/202403/W020240307517480429287.pdf`
  window.open(searchUrl, '_blank')
}
const openQccSearch = () => {
  if (formData.inspectedCompany?.trim()) {
    const searchUrl = `https://www.tianyancha.com/nsearch?key=${encodeURIComponent(formData.inspectedCompany.trim())}`
    window.open(searchUrl, '_blank')
  }
}

// 列向下复制：将第一行该列的值覆盖到其余行
const confirmCopyDown = async (listRef: any, field: string) => {
  try {
    // 兼容模板自动解包：既支持传入 Ref<Array> 也支持传入 Array 本身
    const list: any[] | undefined = Array.isArray(listRef) ? listRef : listRef?.value
    if (!Array.isArray(list) || list.length === 0) {
      ElMessage.warning('当前无数据，无法复制')
      return
    }
    if (list.length < 2) {
      ElMessage.warning('仅一行数据，无需复制')
      return
    }
    const firstVal = list[0]?.[field]
    const display = Array.isArray(firstVal)
      ? (firstVal as any[]).join(',')
      : (firstVal ?? '')
    await ElMessageBox.confirm(
      `第一行中的${display}，会向下覆盖，请确认`,
      '提示',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    for (let i = 1; i < list.length; i++) {
      // 深拷贝数组等引用类型，避免联动引用
      list[i][field] = Array.isArray(firstVal) ? [...(firstVal as any[])] : firstVal
    }
    ElMessage.success('已向下复制')
  } catch (e) {
    // 用户取消
  }
}

// 初始化方法
const initForm = async () => {
  const { projectId, projectNo } = route.query
  formData.projectId = projectId?.toString()
  formData.projectNo = projectNo?.toString()

  const getProjectFieldSurvey = async () => {
    try {
      const data = await ProjectApi.getProjectFieldSurvey(Number(projectId))

      // 直接使用返回的数据结构
      if (data) {
        const {
          process,
          materials,
          intermediate,
          equipment,
          protection,
          facilities,
          basicInfo,
          products,
          layout, // 添加平面布局
          equipmentLayout // 添加设备布局
        } = data

        // 赋值基本信息
        if (basicInfo) {
          Object.assign(formData, basicInfo)
          // 如果已有行业数据，尝试获取对应的风险等级
          if (basicInfo.industry && !basicInfo.riskLevel) {
            initializeIndustryData(basicInfo.industry)
          }
          // 如果已有行业和职工人数数据，加载企业规模选项（初始化时不触发闪烁）
          if (basicInfo.industry && basicInfo.totalEmployees) {
            // loadCompanySizeOptionsForInit(basicInfo.industry, basicInfo.totalEmployees)
          }
        }

        // 赋值各个列表数据
        if (equipment) {
          equipmentList.value = equipment
        }
        if (materials) {
          materialsList.value = materials
        }
        if (products) {
          productsList.value = products
        }
        if (intermediate) {
          intermediateList.value = intermediate
        }
        if (process) {
          processList.value = process
        }
        if (protection) {
          protectionList.value = protection
        }
        if (facilities) {
          facilitiesList.value = facilities
        }
        // 添加平面布局和设备布局数据的初始化
        if (layout) {
          layoutList.value = layout
          console.log('初始化平面布局数据:', layout)
        }
        if (equipmentLayout) {
          equipmentLayoutList.value = equipmentLayout
          console.log('初始化设备布局数据:', equipmentLayout)
        }
      }
    } catch (error) {
      console.error('获取项目详情失败:', error)
    }
  }

  const getProjectDetail = async () => {
    try {
      const data = await ProjectApi.getProject(Number(projectId))
      const { companyName, receivingUnit, status,receivingAddress } = data
      console.log('statusstatusstatusstatus', receivingAddress, status === 33)
      console.log('companyName11', companyName, )
      console.log('receivingUnit11', receivingUnit, )
      console.log('status11', status, )
      console.log('receivingAddress11', receivingAddress)
      hasUnknownResults.value = status === 33
      // 受检单位为空时，取 companyName
      if (!formData.inspectedCompany?.trim()) {
        formData.inspectedCompany = companyName
      }
      // 委托单位为空时，取 receivingUnit
      if (!formData.entrustCompany?.trim()) {
        formData.entrustCompany = receivingUnit
      }
      // 单位注册地址为空时，取 receivingAddress
      if (!formData.registeredAddress?.trim()) {
        formData.registeredAddress = receivingAddress
      }
      // 技术服务地址为空时，取 receivingAddress
      if (!formData.workplaceAddress?.trim()) {
        formData.workplaceAddress = receivingAddress
      }
    } catch (error) {
      console.error('获取项目详情失败:', error)
    }
  }

  // 调用初始化方法（顺序执行，避免并发覆盖导致的闪烁与回退）
  try {
    await getProjectFieldSurvey()
    await getProjectDetail()
    await loadEnterpriseTypes()
  } finally {
    // 所有初始化完成后，启用数据监听
    isInitializing.value = false
    // 初始化完成后，允许用户操作触发闪动效果
    isUserAction.value = true
  }
}

// 删除行
const handleDelete = (index: number) => {
  equipmentList.value.splice(index, 1)
}

// 复制原辅材料行
const handleMaterialCopy = (index: number) => {
  const itemToCopy = { ...materialsList.value[index] }
  materialsList.value.splice(index + 1, 0, itemToCopy)
}

const handleMaterialDelete = (index: number) => {
  materialsList.value.splice(index, 1)
}

const handleProductDelete = (index: number) => {
  productsList.value.splice(index, 1)
}

const handleIntermediateDelete = (index: number) => {
  intermediateList.value.splice(index, 1)
}

// 复制中间产物行
const handleIntermediateCopy = (index: number) => {
  const itemToCopy = { ...intermediateList.value[index] }
  intermediateList.value.splice(index + 1, 0, itemToCopy)
}

// 复制主要产品行
const handleProductCopy = (index: number) => {
  const itemToCopy = { ...productsList.value[index] }
  productsList.value.splice(index + 1, 0, itemToCopy)
}

const handleProcessDelete = (index: number) => {
  processList.value.splice(index, 1)
}

// 复制设备行
const handleEquipmentCopy = (index: number) => {
  const itemToCopy = { ...equipmentList.value[index] }
  equipmentList.value.splice(index + 1, 0, itemToCopy)
}

// 复制防护设施行
const handleFacilityCopy = (index: number) => {
  const itemToCopy = { ...facilitiesList.value[index] }
  facilitiesList.value.splice(index + 1, 0, itemToCopy)
}

// 复制个人防护用品行
const handleProtectionCopy = (index: number) => {
  const itemToCopy = { ...protectionList.value[index] }
  protectionList.value.splice(index + 1, 0, itemToCopy)
}

const handleProtectionDelete = (index: number) => {
  protectionList.value.splice(index, 1)
}

const handleFacilityDelete = (index: number) => {
  facilitiesList.value.splice(index, 1)
}

// 修改 printAllData 方法
const printAllData = async () => {
  // 先验证表单
  if (formRef.value) {
    try {
      await formRef.value.validate()
    } catch (error) {
      console.log('表单验证失败，不保存数据:', error)
      return
    }
  }

  // 在构造数据前同步多地址回表单
  syncWorkplaceAddressForSave()

  const allData = {
    basicInfo: Object.keys(formData).length > 0 ? { ...formData } : {},
    equipment: equipmentList.value.length > 0 ? [...equipmentList.value] : [],
    materials: materialsList.value.length > 0 ? [...materialsList.value] : [],
    products: productsList.value.length > 0 ? [...productsList.value] : [],
    intermediate: intermediateList.value.length > 0 ? [...intermediateList.value] : [],
    process: processList.value.length > 0 ? [...processList.value] : [],
    protection: protectionList.value.length > 0 ? [...protectionList.value] : [],
    facilities: facilitiesList.value.length > 0 ? [...facilitiesList.value] : [],
    layout: layoutList.value.length > 0 ? [...layoutList.value] : [],
    equipmentLayout: equipmentLayoutList.value.length > 0 ? [...equipmentLayoutList.value] : [],
    job: {}
  }

  // 构造接口所需的参数格式
  const params = {
    fieldSurvey: {
      ...allData
    }
  }
  // 调用更新接口
  ProjectApi.updateProjectFieldSurvey(params)
    .then(() => {
      console.log('数据保存成功')
      ElMessage.success('修改成功')
    })
    .catch((error) => {
      console.error('数据保存失败:', error)
    })
}

// 监听单位性质变化，更新展开的节点
watch(
  () => formData.companyNature,
  () => {
    updateExpandedKeys()
  }
)

// 监听所有数据变化
watch(
  [
    formData,
    equipmentList,
    materialsList,
    productsList,
    intermediateList,
    processList,
    protectionList,
    facilitiesList,
    layoutList,
    equipmentLayoutList,
    workplaceAddresses
  ],
  () => {
    // 只有在非初始化状态时才保存数据
    if (!isInitializing.value) {
      // 同步多地址回单字段，避免未触发保存时丢失
      syncWorkplaceAddressForSave()
      printAllData()
    }
  },
  { deep: true }
)

// 在 script 部分添加新增方法
// ==================== 设备相关方法 ====================

// 添加一行设备
const addEquipmentRow = () => {
  equipmentFormList.value.push({
    equipmentName: '',
    quantity: '',
    runningQuantity: '',
    specification: '',
    equipmentLayout: '',
    workshops: []
  })
}

// 删除一行设备
const removeEquipmentRow = (index: number) => {
  if (equipmentFormList.value.length > 1) {
    equipmentFormList.value.splice(index, 1)
  }
}

// 设备新增方法
const handleAddEquipment = async () => {
  // 加载 type=1 的车间/岗位数据

  // 重置表单数据
  equipmentFormList.value = [
    {
      equipmentName: '',
      quantity: '',
      runningQuantity: '',
      specification: '',
      equipmentLayout: '',
      workshops: []
    }
  ]
  // 打开弹窗
  equipmentDialogVisible.value = true
}

// 验证设备单行数据
const validateEquipmentRow = (row: any, index: number) => {
  if (!row.equipmentName.trim()) {
    ElMessage.error(`第${index + 1}行：请输入设备名称`)
    return false
  }
  if (!row.quantity || row.quantity <= 0) {
    ElMessage.error(`第${index + 1}行：请输入有效的数量`)
    return false
  }
  if (!row.runningQuantity || row.runningQuantity < 0) {
    ElMessage.error(`第${index + 1}行：请输入有效的运行数量`)
    return false
  }
  if (!row.equipmentLayout.trim()) {
    ElMessage.error(`第${index + 1}行：请选择设备布局`)
    return false
  }
  if (row.workshops.length === 0) {
    ElMessage.error(`第${index + 1}行：请选择生产车间/岗位/地点`)
    return false
  }
  return true
}

// 确认新增设备
const handleEquipmentConfirm = () => {
  // 验证所有行的数据
  for (let i = 0; i < equipmentFormList.value.length; i++) {
    const row = equipmentFormList.value[i]
    if (!validateEquipmentRow(row, i)) {
      return
    }
  }

  // 添加所有有效的数据
  let addedCount = 0
  equipmentFormList.value.forEach((row) => {
    // 为每个选中的车间/岗位创建一条记录
    row.workshops.forEach((workshop) => {
      equipmentList.value.push({
        workshop: workshop,
        equipmentName: row.equipmentName,
        specification: row.specification,
        quantity: row.quantity,
        runningQuantity: row.runningQuantity,
        equipmentLayout: row.equipmentLayout
      })
      addedCount++
    })
  })

  // 关闭弹窗
  equipmentDialogVisible.value = false
  ElMessage.success(`成功添加${addedCount}条设备记录`)
}

// 取消新增设备
const handleEquipmentCancel = () => {
  equipmentDialogVisible.value = false
}

// 添加一行原辅材料
const addMaterialRow = () => {
  materialFormList.value.push({
    materialName: '',
    usage: '',
    physicalState: '',
    ingredient: '',
    workshops: []
  })
}

// 删除一行原辅材料
const removeMaterialRow = (index: number) => {
  if (materialFormList.value.length > 1) {
    materialFormList.value.splice(index, 1)
  }
}

// 获取车间/岗位数据（按 type 缓存）
const loadWorkshopOptions = async (type: number) => {
  try {
    const data = await ProjectApi.getWorkShopPositionName(Number(route.query.projectId), type)
    console.log('获取工作车间/岗位数据成功:', { type, data })

    if (data && Array.isArray(data)) {
      // 确保数据去重
      const uniqueData = Array.from(new Set(data))
      workshopOptionsCache.value[type] = uniqueData

      // 只更新当前类型的选项，不合并其他类型的数据
      workshopOptions.value = [...uniqueData]
      return true
    }
    return false
  } catch (error) {
    console.error('获取工作车间/岗位数据失败:', error)
    throw error
  }
}

// 确保在下拉展开时按需加载（可见时触发）
const ensureWorkshopOptions = async (type: number) => {
  try {
    await loadWorkshopOptions(type)
  } catch (e) {
    // 静默失败以避免阻断下拉
  }
}

// 处理车间/岗位选择变化 - 根据当前活动的tab确定数据类型
const handleWorkshopChange = (value: string | string[]) => {
  // 根据当前活动的tab确定数据类型
  let currentType = 1 // 默认类型1

  // 根据当前tab确定类型
  if (
    activeTab.value === 'materials' ||
    activeTab.value === 'intermediate' ||
    activeTab.value === 'equipment'
  ) {
    currentType = 1 // 原辅材料、中间产物、主要设备使用type=1
  } else if (activeTab.value === 'protection' || activeTab.value === 'facilities') {
    currentType = 2 // 个人防护、防护设施使用type=2
  } else if (activeTab.value === 'equipment-layout') {
    currentType = 3 // 设备布局使用type=3
  }

  // 添加新选项到列表的辅助函数
  const addNewOption = (newValue: string) => {
    if (!newValue || newValue.trim() === '') return

    const trimmedValue = newValue.trim()

    // 使用Set确保唯一性，然后更新当前显示的选项列表
    const currentOptionsSet = new Set(workshopOptions.value)
    currentOptionsSet.add(trimmedValue)
    workshopOptions.value = Array.from(currentOptionsSet)

    // 使用Set确保对应类型缓存的唯一性
    if (workshopOptionsCache.value[currentType]) {
      const cacheSet = new Set(workshopOptionsCache.value[currentType])
      cacheSet.add(trimmedValue)
      workshopOptionsCache.value[currentType] = Array.from(cacheSet)
    } else {
      // 如果缓存不存在，创建新的缓存数组
      workshopOptionsCache.value[currentType] = [trimmedValue]
    }
  }

  // 处理单选情况
  if (typeof value === 'string') {
    addNewOption(value)
  }
  // 处理多选情况
  else if (Array.isArray(value)) {
    value.forEach((item) => {
      addNewOption(item)
    })
  }
}

// 为企业类型数据添加value字段
const processEnterpriseTypeData = (data: any[]): EnterpriseTypeOption[] => {
  return data.map((item) => ({
    ...item,
    value: item.label, // 使用label作为value
    children: item.children ? processEnterpriseTypeData(item.children) : []
  }))
}

// 获取企业类型数据
const loadEnterpriseTypes = async () => {
  if (enterpriseTypeLoaded.value) {
    return true
  }

  try {
    const data = await ProjectApi.getEnterpriseTypes()
    console.log('获取企业类型数据成功:', data)

    if (data && Array.isArray(data)) {
      // 处理数据，为每个节点添加value字段
      enterpriseTypeOptions.value = processEnterpriseTypeData(data)
      enterpriseTypeLoaded.value = true
      console.log('处理后的企业类型数据:', enterpriseTypeOptions.value)

      // 初始化展开的节点
      updateExpandedKeys()

      return true
    }
    return false
  } catch (error) {
    console.error('获取企业类型数据失败:', error)
    ElMessage.error('获取企业类型数据失败，请稍后重试')
    throw error
  }
}

// 递归查找包含指定值的节点路径
const findNodePath = (
  nodes: EnterpriseTypeOption[],
  targetValue: string,
  path: string[] = []
): string[] | null => {
  for (const node of nodes) {
    const currentPath = [...path, node.value]

    if (node.value === targetValue) {
      return currentPath
    }

    if (node.children && node.children.length > 0) {
      const result = findNodePath(node.children, targetValue, currentPath)
      if (result) {
        return result
      }
    }
  }
  return null
}

// 更新展开的节点
const updateExpandedKeys = () => {
  if (!formData.companyNature || !enterpriseTypeOptions.value.length) {
    expandedKeys.value = []
    return
  }

  const path = findNodePath(enterpriseTypeOptions.value, formData.companyNature)
  if (path && path.length > 1) {
    // 展开到选中节点的父级路径（不包括选中节点本身）
    expandedKeys.value = path.slice(0, -1)
  } else {
    expandedKeys.value = []
  }
}

// 获取展开的节点keys
const getExpandedKeys = () => {
  return expandedKeys.value
}

// 处理树选择器显示状态变化
const handleTreeSelectVisibleChange = (visible: boolean) => {
  if (visible) {
    // 当树选择器打开时，更新展开的节点
    updateExpandedKeys()
  }
}

// 闪动效果函数
const triggerFlash = (type: 'riskLevel' | 'companySize') => {
  // 只有在用户操作时才触发闪动效果，初始化时不触发
  if (!isUserAction.value) {
    return
  }

  if (type === 'riskLevel') {
    riskLevelFlashing.value = true
    setTimeout(() => {
      riskLevelFlashing.value = false
    }, 2000)
  } else if (type === 'companySize') {
    companySizeFlashing.value = true
    setTimeout(() => {
      companySizeFlashing.value = false
    }, 2000)
  }
}

// 获取企业规模数据并直接填充（用户操作版本，触发闪烁）
const loadCompanySizeOptions = async (industry: string, totalEmployees: string | number) => {
  if (!industry || !totalEmployees) {
    return
  }

  try {
    companySizeLoading.value = true
    const data = await ProjectApi.getThreshold(industry, totalEmployees)
    console.log('获取企业规模数据成功:', data)

    if (data) {
      // 直接填充到企业规模字段
      if (typeof data === 'string') {
        formData.companySize = data
      } else if (Array.isArray(data) && data.length > 0) {
        formData.companySize = data[0] // 如果返回数组，取第一个
      }

      // 触发闪动效果
      triggerFlash('companySize')
    }
  } catch (error) {
    console.error('获取企业规模数据失败:', error)
    ElMessage.error('获取企业规模数据失败，请稍后重试')
  } finally {
    companySizeLoading.value = false
  }
}

// 搜索行业分类（带防抖处理）
const searchIndustries = (query: string) => {
  if (!query || query.trim().length < 1) {
    industryOptions.value = []
    return
  }

  // 清除之前的定时器
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }

  // 设置新的定时器，300ms后执行搜索
  searchTimeout = setTimeout(async () => {
    industryLoading.value = true
    try {
      const data = await ProjectApi.getEconomicCategories(query.trim())
      console.log('搜索行业分类成功:', data)

      if (data && Array.isArray(data)) {
        industryOptions.value = data
      } else {
        industryOptions.value = []
      }
    } catch (error) {
      console.error('搜索行业分类失败:', error)
      ElMessage.error('搜索行业分类失败，请稍后重试')
      industryOptions.value = []
    } finally {
      industryLoading.value = false
    }
  }, 300)
}

// 处理行业选择变化
const handleIndustryChange = (value: string) => {
  // 标记为用户操作
  isUserAction.value = true

  // 找到选中的行业数据，现在value是"代码+名称"的格式
  const selectedIndustry = industryOptions.value.find(
    (item) => item.xiaoLeiCode + item.categoryName === value
  )
  if (selectedIndustry) {
    selectedIndustryData.value = selectedIndustry
    // 自动填充风险等级
    const oldRiskLevel = formData.riskLevel
    formData.riskLevel = selectedIndustry.risk

    // 如果风险等级发生变化，触发闪动效果
    if (oldRiskLevel !== selectedIndustry.risk) {
      triggerFlash('riskLevel')
    }

    console.log('选中行业:', selectedIndustry)

    // 当行业变化时，重新获取企业规模选项
    if (formData.totalEmployees) {
      loadCompanySizeOptions(value, formData.totalEmployees)
    }
  } else {
    selectedIndustryData.value = null
    const oldRiskLevel = formData.riskLevel
    formData.riskLevel = ''

    // 如果风险等级被清空，也触发闪动效果
    if (oldRiskLevel !== '') {
      triggerFlash('riskLevel')
    }
  }
}

// 处理在册职工总人数变化
const handleTotalEmployeesChange = (value: string) => {
  // 标记为用户操作
  isUserAction.value = true

  // 当职工人数变化时，重新获取企业规模并直接填充
  if (formData.industry && value) {
    loadCompanySizeOptions(formData.industry, value)
  }
}

// 处理在册职工总人数变化并验证
const handleTotalEmployeesChangeAndValidate = (value: string) => {
  handleTotalEmployeesChange(value)
  validateField('totalEmployees')
}

// 手动验证单个字段
const validateField = (fieldName: string) => {
  if (formRef.value) {
    formRef.value.validateField(fieldName)
  }
}

// 处理同步完成事件
const handleSyncCompleted = () => {
  // 同步完成后清除提示
  hasUnknownResults.value = false
}

// 直接搜索行业分类（不带防抖，用于初始化）
const searchIndustriesImmediate = async (query: string) => {
  if (!query || query.trim().length < 1) {
    return []
  }

  try {
    const data = await ProjectApi.getEconomicCategories(query.trim())
    console.log('直接搜索行业分类成功:', data)

    if (data && Array.isArray(data)) {
      return data
    }
    return []
  } catch (error) {
    console.error('直接搜索行业分类失败:', error)
    return []
  }
}

// 初始化行业数据（用于页面加载时已有行业数据的情况）
const initializeIndustryData = async (industryName: string) => {
  try {
    // 判断industryName的格式，可能是纯名称或者"代码+名称"格式
    let searchQuery = ''
    let isCodeNameFormat = false

    // 检查是否是"代码+名称"格式（以字母开头）
    if (/^[A-Z]\d+/.test(industryName)) {
      // 提取名称部分进行搜索
      const match = industryName.match(/^[A-Z]\d+(.+)/)
      if (match) {
        searchQuery = match[1].substring(0, 3)
        isCodeNameFormat = true
      }
    } else {
      // 纯名称格式
      searchQuery = industryName.substring(0, 3)
    }

    const searchResults = await searchIndustriesImmediate(searchQuery)

    // 在搜索结果中查找匹配的行业
    let matchedIndustry = null
    if (isCodeNameFormat) {
      // 按"代码+名称"格式匹配
      matchedIndustry = searchResults.find(
        (item) => item.xiaoLeiCode + item.categoryName === industryName
      )
    } else {
      // 按纯名称匹配
      matchedIndustry = searchResults.find((item) => item.categoryName === industryName)
      // 如果找到了，需要更新formData.industry为新格式
      if (matchedIndustry) {
        formData.industry = matchedIndustry.xiaoLeiCode + matchedIndustry.categoryName
      }
    }

    if (matchedIndustry) {
      selectedIndustryData.value = matchedIndustry
      // 将匹配的行业添加到选项中，以便下拉框能正确显示
      industryOptions.value = [matchedIndustry]
      // 如果当前没有风险等级，则自动填充（初始化时不触发闪动效果）
      if (!formData.riskLevel) {
        formData.riskLevel = matchedIndustry.risk
        // 初始化时不触发闪动效果
      }
      console.log('初始化行业数据成功:', matchedIndustry)
    }
  } catch (error) {
    console.error('初始化行业数据失败:', error)
  }
}

// 原辅材料新增方法
const handleAddMaterial = async () => {
  // 重置表单数据
  materialFormList.value = [
    {
      materialName: '',
      usage: '',
      physicalState: '',
      ingredient: '',
      workshops: []
    }
  ]
  // 打开弹窗
  materialDialogVisible.value = true
}

// 验证单行数据
const validateMaterialRow = (row: any, index: number) => {
  if (!row.materialName.trim()) {
    ElMessage.error(`第${index + 1}行：请输入辅料名称`)
    return false
  }
  if (!row.usage.trim()) {
    ElMessage.error(`第${index + 1}行：请输入用量`)
    return false
  }
  if (!row.physicalState.trim()) {
    ElMessage.error(`第${index + 1}行：请输入物理状态`)
    return false
  }
  if (!row.ingredient.trim()) {
    ElMessage.error(`第${index + 1}行：请输入主要成分`)
    return false
  }
  if (row.workshops.length === 0) {
    ElMessage.error(`第${index + 1}行：请选择生产车间/岗位/地点`)
    return false
  }
  return true
}

// 确认新增原辅材料
const handleMaterialConfirm = () => {
  // 验证所有行的数据
  for (let i = 0; i < materialFormList.value.length; i++) {
    const row = materialFormList.value[i]
    if (!validateMaterialRow(row, i)) {
      return
    }
  }

  // 添加所有有效的数据
  let addedCount = 0
  materialFormList.value.forEach((row) => {
    // 为每个选中的车间/岗位创建一条记录
    row.workshops.forEach((workshop) => {
      materialsList.value.push({
        workshop: workshop,
        materialName: row.materialName,
        usage: row.usage,
        physicalState: row.physicalState,
        ingredient: row.ingredient,
        remarks: ''
      })
      addedCount++
    })
  })

  // 关闭弹窗
  materialDialogVisible.value = false
  ElMessage.success(`成功添加${addedCount}条原辅材料记录`)
}

// 取消新增原辅材料
const handleMaterialCancel = () => {
  materialDialogVisible.value = false
}

// ==================== 中间产物相关方法 ====================

// 添加一行中间产物
const addIntermediateRow = () => {
  intermediateFormList.value.push({
    intermediateName: '',
    production: '',
    physicalState: '',
    workshops: []
  })
}

// 删除一行中间产物
const removeIntermediateRow = (index: number) => {
  if (intermediateFormList.value.length > 1) {
    intermediateFormList.value.splice(index, 1)
  }
}

// 中间产物新增方法
const handleAddIntermediate = async () => {
  // 加载 type=1 的车间/岗位数据

  // 重置表单数据
  intermediateFormList.value = [
    {
      intermediateName: '',
      production: '',
      physicalState: '',
      ingredient: '',
      packaging: '',
      workshops: []
    }
  ]
  // 打开弹窗
  intermediateDialogVisible.value = true
}

// 验证中间产物单行数据
const validateIntermediateRow = (row: any, index: number) => {
  if (!row.intermediateName.trim()) {
    ElMessage.error(`第${index + 1}行：请输入中间产物名称`)
    return false
  }
  if (!row.production.trim()) {
    ElMessage.error(`第${index + 1}行：请输入产量/产值`)
    return false
  }
  if (!row.physicalState.trim()) {
    ElMessage.error(`第${index + 1}行：请输入物理状态`)
    return false
  }
  if (!row.ingredient.trim()) {
    ElMessage.error(`第${index + 1}行：请输入主要成分`)
    return false
  }
  if (!row.packaging.trim()) {
    ElMessage.error(`第${index + 1}行：请输入包装方式`)
    return false
  }
  if (row.workshops.length === 0) {
    ElMessage.error(`第${index + 1}行：请选择生产车间/岗位/地点`)
    return false
  }
  return true
}

// 确认新增中间产物
const handleIntermediateConfirm = () => {
  // 验证所有行的数据
  for (let i = 0; i < intermediateFormList.value.length; i++) {
    const row = intermediateFormList.value[i]
    if (!validateIntermediateRow(row, i)) {
      return
    }
  }

  // 添加所有有效的数据
  let addedCount = 0
  intermediateFormList.value.forEach((row) => {
    // 为每个选中的车间/岗位创建一条记录
    row.workshops.forEach((workshop) => {
      intermediateList.value.push({
        workshop: workshop,
        intermediateName: row.intermediateName,
        production: row.production,
        physicalState: row.physicalState,
        ingredient: row.ingredient,
        packaging: row.packaging
      })
      addedCount++
    })
  })

  // 关闭弹窗
  intermediateDialogVisible.value = false
  ElMessage.success(`成功添加${addedCount}条中间产物记录`)
}

// 取消新增中间产物
const handleIntermediateCancel = () => {
  intermediateDialogVisible.value = false
}

// 主产品新增方法
const handleAddProduct = () => {
  productsList.value.push({
    productName: '',
    production: '',
    physicalState: '',
    packaging: '',
    composition: ''
  })
}

// 工艺流程新增方法
const handleAddProcess = () => {
  processList.value.push({
    processName: '生产工艺流程',
    processImages: [],
    processDescription: ''
  })
}

// ==================== 个人防护用品相关方法 ====================

// 添加一行个人防护用品
const addProtectionRow = () => {
  protectionFormList.value.push({
    protectionType: '',
    protectionName: '',
    manufacturer: '',
    specification: '',
    replacementCycle: '',
    workshops: []
  })
}

// 删除一行个人防护用品
const removeProtectionRow = (index: number) => {
  if (protectionFormList.value.length > 1) {
    protectionFormList.value.splice(index, 1)
  }
}

// 个人防护用品新增方法
const handleAddProtection = async () => {
  // 加载 type=2 的车间/岗位数据
  // 重置表单数据
  protectionFormList.value = [
    {
      protectionType: '',
      protectionName: '',
      manufacturer: '',
      specification: '',
      replacementCycle: '',
      workshops: []
    }
  ]
  // 打开弹窗
  protectionDialogVisible.value = true
}

// 验证个人防护用品单行数据
const validateProtectionRow = (row: any, index: number) => {
  if (!row.protectionType.trim()) {
    ElMessage.error(`第${index + 1}行：请选择职业病防护用品类别`)
    return false
  }
  if (!row.protectionName.trim()) {
    ElMessage.error(`第${index + 1}行：请选择防护用品名称`)
    return false
  }
  if (row.workshops.length === 0) {
    ElMessage.error(`第${index + 1}行：请选择生产车间/岗位/地点`)
    return false
  }
  return true
}

// 确认新增个人防护用品
const handleProtectionConfirm = () => {
  // 验证所有行的数据
  for (let i = 0; i < protectionFormList.value.length; i++) {
    const row = protectionFormList.value[i]
    if (!validateProtectionRow(row, i)) {
      return
    }
  }

  // 添加所有有效的数据
  let addedCount = 0
  protectionFormList.value.forEach((row) => {
    // 为每个选中的车间/岗位创建一条记录
    row.workshops.forEach((workshop) => {
      protectionList.value.push({
        workshop: workshop,
        protectionType: row.protectionType,
        protectionName: row.protectionName,
        manufacturer: row.manufacturer,
        specification: row.specification,
        position: '',
        replacementCycle: row.replacementCycle
      })
      addedCount++
    })
  })

  // 关闭弹窗
  protectionDialogVisible.value = false
  ElMessage.success(`成功添加${addedCount}条个人防护用品记录`)
}

// 取消新增个人防护用品
const handleProtectionCancel = () => {
  protectionDialogVisible.value = false
}

// ==================== 防护设施相关方法 ====================

// 添加一行防护设施
const addFacilitiesRow = () => {
  facilitiesFormList.value.push({
    facilityType: '',
    facilityName: '',
    total: '',
    running: '',
    workshops: []
  })
}
// 删除一行防护设施
const removeFacilitiesRow = (index: number) => {
  if (facilitiesFormList.value.length > 1) {
    facilitiesFormList.value.splice(index, 1)
  }
}

// 防护设施新增方法
const handleAddFacility = async () => {
  // 重置表单数据
  facilitiesFormList.value = [
    {
      facilityType: '',
      facilityName: '',
      total: '',
      running: '',
      workshops: []
    }
  ]
  // 打开弹窗
  facilitiesDialogVisible.value = true
}

// 验证防护设施单行数据
const validateFacilitiesRow = (row: any, index: number) => {
  if (!row.facilityName.trim()) {
    ElMessage.error(`第${index + 1}行：请输入防护设施名称`)
    return false
  }
  if (!row.total || row.total <= 0) {
    ElMessage.error(`第${index + 1}行：请输入有效的总数`)
    return false
  }
  if (!row.running || row.running <= 0) {
    ElMessage.error(`第${index + 1}行：请输入有效的运行数`)
    return false
  }
  if (row.workshops.length === 0) {
    ElMessage.error(`第${index + 1}行：请选择生产车间/岗位/地点`)
    return false
  }
  return true
}

// 确认新增防护设施
const handleFacilitiesConfirm = () => {
  // 验证所有行的数据
  for (let i = 0; i < facilitiesFormList.value.length; i++) {
    const row = facilitiesFormList.value[i]
    if (!validateFacilitiesRow(row, i)) {
      return
    }
  }

  // 添加所有有效的数据
  let addedCount = 0
  facilitiesFormList.value.forEach((row) => {
    // 为每个选中的车间/岗位创建一条记录
    row.workshops.forEach((workshop) => {
      facilitiesList.value.push({
        workshop: workshop,
        position: '',
        facilityType: row.facilityType,
        facilityName: row.facilityName,
        total: row.total,
        running: row.running
      })
      addedCount++
    })
  })

  // 关闭弹窗
  facilitiesDialogVisible.value = false
  ElMessage.success(`成功添加${addedCount}条防护设施记录`)
}

// 取消新增防护设施
const handleFacilitiesCancel = () => {
  facilitiesDialogVisible.value = false
}

// 处理图片上传
const handleProcessImageUpload = async (file: File, index: number) => {
  try {
    // 检查文件类型
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
    if (!allowedTypes.includes(file.type)) {
      ElMessage.error('只支持 JPG、PNG、GIF 格式的图片')
      return false
    }

    // 创建 UploadRawFile
    const rawFile: UploadRawFile = Object.assign(file, {
      uid: Date.now()
    })

    // 使用 useUpload 上传文件
    const result = await httpRequest({
      file: rawFile,
      filename: file.name,
      data: {},
      headers: {},
      action: '',
      method: 'post',
      onProgress: () => {},
      onError: () => {},
      onSuccess: () => {},
      withCredentials: false
    })

    if (result && typeof result === 'object' && 'data' in result) {
      // 将返回的URL添加到图片列表中
      processList.value[index].processImages.push(result.data as string)
      ElMessage.success('图片上传成功')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  }
  return false // 阻止自动上传
}

// 删除图片
const handleProcessImageRemove = (index: number, imageIndex: number) => {
  processList.value[index].processImages.splice(imageIndex, 1)
}

// 平面布局新增方法
const handleAddLayout = () => {
  layoutList.value.push({
    layoutImages: []
  })
}

// 设备布局新增方法
const handleAddEquipmentLayout = () => {
  // 加载 type=3 的工作场所数据
  loadWorkshopOptions(3).catch((error) => {
    console.error('获取工作场所数据失败:', error)
    ElMessage.error('获取工作场所数据失败，请稍后重试')
  })
  equipmentLayoutList.value.push({
    workplace: '',
    layoutImages: []
  })
}

// 处理平面布局图片上传
const handleLayoutImageUpload = async (file: File, index: number) => {
  try {
    // 检查文件类型
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
    if (!allowedTypes.includes(file.type)) {
      ElMessage.error('只支持 JPG、PNG、GIF 格式的图片')
      return false
    }

    // 创建 UploadRawFile
    const rawFile: UploadRawFile = Object.assign(file, {
      uid: Date.now()
    })

    // 使用 useUpload 上传文件
    const result = await httpRequest({
      file: rawFile,
      filename: file.name,
      data: {},
      headers: {},
      action: '',
      method: 'post',
      onProgress: () => {},
      onError: () => {},
      onSuccess: () => {},
      withCredentials: false
    })

    if (result && typeof result === 'object' && 'data' in result) {
      // 将返回的URL添加到图片列表中
      layoutList.value[index].layoutImages.push(result.data as string)
      ElMessage.success('图片上传成功')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  }
  return false
}

// 处理设备布局图片上传
const handleEquipmentLayoutImageUpload = async (file: File, index: number) => {
  try {
    // 检查文件类型
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
    if (!allowedTypes.includes(file.type)) {
      ElMessage.error('只支持 JPG、PNG、GIF 格式的图片')
      return false
    }

    // 创建 UploadRawFile
    const rawFile: UploadRawFile = Object.assign(file, {
      uid: Date.now()
    })

    // 使用 useUpload 上传文件
    const result = await httpRequest({
      file: rawFile,
      filename: file.name,
      data: {},
      headers: {},
      action: '',
      method: 'post',
      onProgress: () => {},
      onError: () => {},
      onSuccess: () => {},
      withCredentials: false
    })

    if (result && typeof result === 'object' && 'data' in result) {
      // 将返回的URL添加到图片列表中
      equipmentLayoutList.value[index].layoutImages.push(result.data as string)
      ElMessage.success('图片上传成功')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  }
  return false
}

// 删除平面布局图片
const handleLayoutImageRemove = (index: number, imageIndex: number) => {
  layoutList.value[index].layoutImages.splice(imageIndex, 1)
}

// 删除设备布局图片
const handleEquipmentLayoutImageRemove = (index: number, imageIndex: number) => {
  equipmentLayoutList.value[index].layoutImages.splice(imageIndex, 1)
}

// 删除平面布局行
const handleLayoutDelete = (index: number) => {
  layoutList.value.splice(index, 1)
}

// 删除设备布局行
const handleEquipmentLayoutDelete = (index: number) => {
  equipmentLayoutList.value.splice(index, 1)
}

// 原辅材料表格合并方法
const materialsSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  // 只对前四列进行合并：原辅材料名称、用量、物理状态、主要成分
  if (columnIndex >= 0 && columnIndex <= 3) {
    const currentRow = materialsList.value[rowIndex]

    // 检查当前行的前四个字段是否都不为空
    if (
      !currentRow.materialName?.trim() ||
      !currentRow.usage?.trim() ||
      !currentRow.physicalState?.trim() ||
      !currentRow.ingredient?.trim()
    ) {
      return { rowspan: 1, colspan: 1 }
    }

    // 计算相同数据的行数
    let rowspan = 1
    let startIndex = rowIndex

    // 向上查找相同的行
    for (let i = rowIndex - 1; i >= 0; i--) {
      const prevRow = materialsList.value[i]
      if (
        prevRow.materialName === currentRow.materialName &&
        prevRow.usage === currentRow.usage &&
        prevRow.physicalState === currentRow.physicalState &&
        prevRow.ingredient === currentRow.ingredient &&
        prevRow.materialName?.trim() &&
        prevRow.usage?.trim() &&
        prevRow.physicalState?.trim() &&
        prevRow.ingredient?.trim()
      ) {
        startIndex = i
      } else {
        break
      }
    }

    // 向下查找相同的行
    for (let i = rowIndex + 1; i < materialsList.value.length; i++) {
      const nextRow = materialsList.value[i]
      if (
        nextRow.materialName === currentRow.materialName &&
        nextRow.usage === currentRow.usage &&
        nextRow.physicalState === currentRow.physicalState &&
        nextRow.ingredient === currentRow.ingredient &&
        nextRow.materialName?.trim() &&
        nextRow.usage?.trim() &&
        nextRow.physicalState?.trim() &&
        nextRow.ingredient?.trim()
      ) {
        rowspan++
      } else {
        break
      }
    }

    // 如果是第一行，返回合并的行数
    if (rowIndex === startIndex) {
      return { rowspan: rowspan, colspan: 1 }
    } else {
      // 如果不是第一行，隐藏该单元格
      return { rowspan: 0, colspan: 0 }
    }
  }

  // 其他列正常显示
  return { rowspan: 1, colspan: 1 }
}

// 中间产物表格合并方法
const intermediateSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  // 根据实际表格列顺序：0=中间产物、副产品、联产产品名称, 1=产量/产值, 2=物理状态, 3=主要成分, 4=包装方式, 5=生产车间/岗位
  // 只对前五列进行合并：中间产物、副产品、联产产品名称、产量/产值、物理状态、主要成分、包装方式
  if (columnIndex >= 0 && columnIndex <= 4) {
    const currentRow = intermediateList.value[rowIndex]

    // 检查当前行的前五个字段是否都不为空
    if (
      !currentRow.intermediateName?.trim() ||
      !currentRow.production?.trim() ||
      !currentRow.physicalState?.trim() ||
      !currentRow.ingredient?.trim() ||
      !currentRow.packaging?.trim()
    ) {
      return { rowspan: 1, colspan: 1 }
    }

    // 计算相同数据的行数
    let rowspan = 1
    let startIndex = rowIndex

    // 向上查找相同的行
    for (let i = rowIndex - 1; i >= 0; i--) {
      const prevRow = intermediateList.value[i]
      if (
        prevRow.intermediateName === currentRow.intermediateName &&
        prevRow.production === currentRow.production &&
        prevRow.physicalState === currentRow.physicalState &&
        prevRow.ingredient === currentRow.ingredient &&
        prevRow.packaging === currentRow.packaging &&
        prevRow.intermediateName?.trim() &&
        prevRow.production?.trim() &&
        prevRow.physicalState?.trim() &&
        prevRow.ingredient?.trim() &&
        prevRow.packaging?.trim()
      ) {
        startIndex = i
      } else {
        break
      }
    }

    // 向下查找相同的行
    for (let i = rowIndex + 1; i < intermediateList.value.length; i++) {
      const nextRow = intermediateList.value[i]
      if (
        nextRow.intermediateName === currentRow.intermediateName &&
        nextRow.production === currentRow.production &&
        nextRow.physicalState === currentRow.physicalState &&
        nextRow.ingredient === currentRow.ingredient &&
        nextRow.packaging === currentRow.packaging &&
        nextRow.intermediateName?.trim() &&
        nextRow.production?.trim() &&
        nextRow.physicalState?.trim() &&
        nextRow.ingredient?.trim() &&
        nextRow.packaging?.trim()
      ) {
        rowspan++
      } else {
        break
      }
    }

    // 如果是第一行，返回合并的行数
    if (rowIndex === startIndex) {
      return { rowspan: rowspan, colspan: 1 }
    } else {
      // 如果不是第一行，隐藏该单元格
      return { rowspan: 0, colspan: 0 }
    }
  }

  // 其他列正常显示
  return { rowspan: 1, colspan: 1 }
}

const getEquipmentLayoutKey = (value: string | string[] | undefined) => {
  if (!value) return ''
  if (Array.isArray(value)) {
    return value
      .map((item) => (typeof item === 'string' ? item.trim() : String(item)))
      .filter((item) => item.length > 0)
      .join('|')
  }
  return typeof value === 'string' ? value.trim() : ''
}

const isEquipmentLayoutFilled = (value: string | string[] | undefined) => {
  return getEquipmentLayoutKey(value) !== ''
}

// 设备表格合并方法
const equipmentSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  // 根据实际表格叶子列顺序：
  // 0=设备名称, 1=数量-总数, 2=数量-运行, 3=规格型号, 4=设备布局, 5=生产车间/岗位, 6=操作
  // 需要合并的列：设备名称、数量(总数/运行)、规格型号、设备布局 → 即前5个叶子列
  if (columnIndex >= 0 && columnIndex <= 4) {
    const currentRow = equipmentList.value[rowIndex]
    const currentLayoutKey = getEquipmentLayoutKey(currentRow.equipmentLayout)

    // 检查当前行的前四个字段是否都不为空
    if (
      !currentRow.equipmentName?.trim() ||
      !currentRow.quantity ||
      !currentRow.runningQuantity ||
      !currentRow.specification?.trim() ||
      !isEquipmentLayoutFilled(currentRow.equipmentLayout)
    ) {
      return { rowspan: 1, colspan: 1 }
    }

    // 计算相同数据的行数
    let rowspan = 1
    let startIndex = rowIndex

    // 向上查找相同的行
    for (let i = rowIndex - 1; i >= 0; i--) {
      const prevRow = equipmentList.value[i]
      const prevLayoutKey = getEquipmentLayoutKey(prevRow.equipmentLayout)
      if (
        prevRow.equipmentName === currentRow.equipmentName &&
        prevRow.quantity === currentRow.quantity &&
        prevRow.runningQuantity === currentRow.runningQuantity &&
        prevRow.specification === currentRow.specification &&
        prevLayoutKey === currentLayoutKey &&
        prevRow.equipmentName?.trim() &&
        prevRow.quantity &&
        prevRow.runningQuantity &&
        prevRow.specification?.trim() &&
        isEquipmentLayoutFilled(prevRow.equipmentLayout)
      ) {
        startIndex = i
      } else {
        break
      }
    }

    // 向下查找相同的行
    for (let i = rowIndex + 1; i < equipmentList.value.length; i++) {
      const nextRow = equipmentList.value[i]
      const nextLayoutKey = getEquipmentLayoutKey(nextRow.equipmentLayout)
      if (
        nextRow.equipmentName === currentRow.equipmentName &&
        nextRow.quantity === currentRow.quantity &&
        nextRow.runningQuantity === currentRow.runningQuantity &&
        nextRow.specification === currentRow.specification &&
        nextLayoutKey === currentLayoutKey &&
        nextRow.equipmentName?.trim() &&
        nextRow.quantity &&
        nextRow.runningQuantity &&
        nextRow.specification?.trim() &&
        isEquipmentLayoutFilled(nextRow.equipmentLayout)
      ) {
        rowspan++
      } else {
        break
      }
    }

    // 如果是第一行，返回合并的行数
    if (rowIndex === startIndex) {
      return { rowspan: rowspan, colspan: 1 }
    } else {
      // 如果不是第一行，隐藏该单元格
      return { rowspan: 0, colspan: 0 }
    }
  }

  // 其他列正常显示
  return { rowspan: 1, colspan: 1 }
}

// 个人防护用品表格合并方法
const protectionSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  // 根据实际表格列顺序：0=职业病防护用品类别, 1=职业病防护用品分类, 2=生产厂家, 3=型号参数, 4=更换周期, 5=生产车间/岗位
  // 只对前五列进行合并：职业病防护用品类别、职业病防护用品分类、生产厂家、型号参数、更换周期
  if (columnIndex >= 0 && columnIndex <= 4) {
    const currentRow = protectionList.value[rowIndex]

    // 检查当前行的前五个字段是否都不为空
    if (!currentRow.protectionType?.trim() || !currentRow.protectionName?.trim()) {
      return { rowspan: 1, colspan: 1 }
    }

    // 计算相同数据的行数
    let rowspan = 1
    let startIndex = rowIndex

    // 向上查找相同的行
    for (let i = rowIndex - 1; i >= 0; i--) {
      const prevRow = protectionList.value[i]
      if (
        prevRow.protectionType === currentRow.protectionType &&
        prevRow.protectionName === currentRow.protectionName &&
        prevRow.manufacturer === currentRow.manufacturer &&
        prevRow.specification === currentRow.specification &&
        prevRow.replacementCycle === currentRow.replacementCycle &&
        prevRow.protectionType?.trim() &&
        prevRow.protectionName?.trim()
      ) {
        startIndex = i
      } else {
        break
      }
    }

    // 向下查找相同的行
    for (let i = rowIndex + 1; i < protectionList.value.length; i++) {
      const nextRow = protectionList.value[i]
      if (
        nextRow.protectionType === currentRow.protectionType &&
        nextRow.protectionName === currentRow.protectionName &&
        nextRow.manufacturer === currentRow.manufacturer &&
        nextRow.specification === currentRow.specification &&
        nextRow.replacementCycle === currentRow.replacementCycle &&
        nextRow.protectionType?.trim() &&
        nextRow.protectionName?.trim()
      ) {
        rowspan++
      } else {
        break
      }
    }

    // 如果是第一行，返回合并的行数
    if (rowIndex === startIndex) {
      return { rowspan: rowspan, colspan: 1 }
    } else {
      // 如果不是第一行，隐藏该单元格
      return { rowspan: 0, colspan: 0 }
    }
  }

  // 其他列正常显示
  return { rowspan: 1, colspan: 1 }
}

// 防护设施表格合并方法
const facilitiesSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  // 根据实际表格列顺序：0=防护设施类型, 1=防护设施名称, 2=总数, 3=运行数, 4=生产车间/岗位
  // 只对前四列进行合并：防护设施类型、防护设施名称、总数、运行数
  if (columnIndex >= 0 && columnIndex <= 3) {
    const currentRow = facilitiesList.value[rowIndex]

    // 检查当前行的前四个字段是否都不为空
    if (!currentRow.facilityName?.trim() || !currentRow.total || !currentRow.running) {
      return { rowspan: 1, colspan: 1 }
    }

    // 计算相同数据的行数
    let rowspan = 1
    let startIndex = rowIndex

    // 向上查找相同的行
    for (let i = rowIndex - 1; i >= 0; i--) {
      const prevRow = facilitiesList.value[i]
      if (
        prevRow.facilityType === currentRow.facilityType &&
        prevRow.facilityName === currentRow.facilityName &&
        prevRow.total === currentRow.total &&
        prevRow.running === currentRow.running &&
        prevRow.facilityName?.trim() &&
        prevRow.total &&
        prevRow.running
      ) {
        startIndex = i
      } else {
        break
      }
    }

    // 向下查找相同的行
    for (let i = rowIndex + 1; i < facilitiesList.value.length; i++) {
      const nextRow = facilitiesList.value[i]
      if (
        nextRow.facilityType === currentRow.facilityType &&
        nextRow.facilityName === currentRow.facilityName &&
        nextRow.total === currentRow.total &&
        nextRow.running === currentRow.running &&
        nextRow.facilityName?.trim() &&
        nextRow.total &&
        nextRow.running
      ) {
        rowspan++
      } else {
        break
      }
    }

    // 如果是第一行，返回合并的行数
    if (rowIndex === startIndex) {
      return { rowspan: rowspan, colspan: 1 }
    } else {
      // 如果不是第一行，隐藏该单元格
      return { rowspan: 0, colspan: 0 }
    }
  }

  // 其他列正常显示
  return { rowspan: 1, colspan: 1 }
}

onMounted(async () => {
  // 设置初始化状态
  isInitializing.value = true

  // 从 localStorage 恢复上次选中的 tab
  const savedTab = localStorage.getItem('fieldSurveyActiveTab')
  if (savedTab) {
    activeTab.value = savedTab
  }
  await initForm()
})

onUnmounted(() => {
  // 清理搜索定时器
  if (searchTimeout) {
    clearTimeout(searchTimeout)
    searchTimeout = null
  }
})
</script>

<style scoped>
.pdf-container {
  width: 100%;
  height: 80vh; /* 视口高度的80%，可根据需求调整 */
  min-height: 500px; /* 可选：设置最小高度 */
}

embed {
  width: 100%;
  height: 100%;
  border: none; /* 移除默认边框 */
}

.field-survey {
  position: relative;
  height: 100%;
  background-color: var(--el-bg-color);
}

/* 表格相关样式 */
.equipment-content {
  padding: 0px;
}

/* 新增按钮容器样式 */
.mb-4 {
  margin: 0px 0 0px;
  padding: 0 0px;
  border-bottom: 1px solid var(--el-border-color-light);
  padding-bottom: 5px;
}

/* 设置表头背景色和其他样式 */
:deep(.el-table__header-wrapper) {
  th.el-table__cell {
    background-color: #f5f7fa !important;
    color: var(--el-text-color-regular);
    font-weight: 500;
  }
}

/* 表格内容样式 */
:deep(.el-table) {
  --el-table-header-bg-color: #f5f7fa;
}

/* 必填项红色星号样式 */
.required-star {
  color: #f56c6c;
  margin-left: 4px;
  font-size: 14px;
}

/* 表格内容居中对齐 */
:deep(.el-table .cell) {
  text-align: center;
}

/* 调整表格内输入框样式 */
:deep(.el-table .el-input__wrapper) {
  padding: 0 8px;
  box-shadow: none;
}

/* 调整操作列按钮间距 */
:deep(.el-table .cell .el-button + .el-button) {
  margin-left: 8px;
}

th,
td {
  white-space: nowrap; /* 不换行 */
  width: 1%; /* 让宽度尽量收缩 */
  padding: 4px 8px; /* 适当内边距 */
}

.preview-button-container {
  position: absolute;
  right: 12px;
  top: 4px;
  z-index: 100;
}

.sync-badge {
  margin-right: 8px;
}

/* 定性同步按钮闪烁效果 */
.flash-sync {
  animation: pulseSync 0.5s ease-in-out infinite;
}

@keyframes pulseSync {
  0% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.6);
  }
  70% {
    box-shadow: 0 0 0 8px rgba(245, 108, 108, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0);
  }
}

.image-upload-container {
  padding: 8px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 8px;
}

.image-item {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid var(--el-border-color-lighter);
  transition: all 0.3s;
}

.image-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}

.delete-button {
  position: absolute;
  right: 4px;
  top: 4px;
  padding: 2px 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-item:hover .delete-button {
  opacity: 1;
}

:deep(.el-image-viewer__wrapper) {
  z-index: 2100;
}

:deep(.el-image-viewer__mask) {
  background: rgba(0, 0, 0, 0.8);
}

:deep(.el-image-viewer__close) {
  color: #fff;
}

:deep(.el-image-viewer__actions__inner) {
  background: rgba(0, 0, 0, 0.5);
  border-radius: 20px;
}

:deep(.el-image-viewer__prev, .el-image-viewer__next) {
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  padding: 10px;
}

:deep(.el-image-viewer__img) {
  background-color: transparent;
}

/* 闪动边框效果 - 红色虚线闪烁 */
.flash-border {
  animation: redDashedFlash 2s ease-in-out;
}

@keyframes redDashedFlash {
  0%,
  100% {
    border: 2px dashed #f56c6c !important;
    box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.3) !important;
  }
  50% {
    border: 2px dashed #f56c6c !important;
    box-shadow: 0 0 0 4px rgba(245, 108, 108, 0.6) !important;
  }
}

/* 为Element Plus的select组件添加红色虚线闪动效果 */
:deep(.flash-border .el-input__wrapper) {
  animation: redDashedFlash 2s ease-in-out !important;
  border: 2px dashed #f56c6c !important;
}

:deep(.flash-border .el-select__wrapper) {
  animation: redDashedFlash 2s ease-in-out !important;
  border: 2px dashed #f56c6c !important;
}

/* 为整个select组件添加闪动效果 */
:deep(.flash-border) {
  animation: redDashedFlash 2s ease-in-out !important;
}

/* 受检单位输入框容器样式 */
.company-input-container {
  display: flex !important;
  align-items: center !important;
  gap: 8px !important;
  width: 100% !important;
}

/* 列向下复制图标样式 */
.copy-down-icon {
  margin-left: 6px;
  cursor: pointer;
  color: var(--el-color-primary);
  vertical-align: middle;
}
.copy-down-icon:hover {
  color: var(--el-color-primary-dark-2);
}

.copy-down-btn {
  margin-left: 6px;
  padding: 0;
  vertical-align: middle;
}
</style>
